package com.iris.live.services.services.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.iris.live.services.common.*;
import com.iris.live.services.common.reconsitution.*;
import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.RequestBase;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.AfterMarketService;
import com.iris.live.services.vo.aftermarket.AfterMarketObj;
import com.iris.live.services.vo.aftermarket.AfterMarketResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by sxy on 2016/8/1
 */
@Service
@Transactional//(readOnly = true)
@PropertySource(value = "classpath:application.${env}.properties")
public class AfterMarketServiceImpl implements AfterMarketService {
    private static Logger logger = LoggerFactory.getLogger(AfterMarketServiceImpl.class);

    @Autowired
    private Environment environment;

    @Autowired
    private AfterMarketRepository repository;

    @Autowired
    private FileRepository fileRepository;

    @Autowired
    private Lsh精品信息Repository lsh精品信息Repository;

    @Autowired
    private Lsh精品图片Repository lsh精品图片Repository;

    @Autowired
    private Lsh套餐信息Repository lsh套餐信息Repository;

    @Autowired
    private Lsh套餐图片Repository lsh套餐图片Repository;

    @Autowired
    private 报价单表Repository 报价单表Repository;

    @Autowired
    private 报价精品详细表精品Repository 报价精品详细表精品repository;

    @Autowired
    private 报价精品详细表Repository 报价精品详细表Repository;

    @Autowired
    private 报价精品表Repository 报价精品表Repository;

    @Autowired
    private Lsh精品促销Repository lsh精品促销Repository;

    @Autowired
    private Lsh随车项目设置repository lsh随车项目设置repository;

    @Autowired
    private Lsh精品套餐详细Repository lsh精品套餐详细Repository;

    @Autowired
    private Lsh套餐适用区域Repository lsh套餐适用区域Repository;

    @Autowired
    private Lsh套餐适用车型Repository lsh套餐适用车型Repository;

    @Autowired
    private Lsh精品种类Repository lsh精品种类Repository;

    @Autowired
    private Lsh精品分类Repository lsh精品分类Repository;

    @Autowired
    private Lsh精品Nc分类Repository lsh精品Nc分类Repository;

    @Autowired
    private Lsh精品适用区域Repository lsh精品适用区域Repository;

    @Autowired
    private Lsh精品适用车型Repository lsh精品适用车型Repository;

    @Autowired
    private Lsh消息Repository lsh消息Repositorys;

    @Autowired
    private Lsh经销商表Repository lsh经销商表Repository;

    @Autowired
    private BusinessticketsRepository businessticketsRepositorys;

    @Autowired
    private TPrdSupplierMailSettingRepository tPrdSupplierMailSettingRepository;

    @Autowired
    private BusinessticketsRelyRepository businessticketsRelyRepository;

    @Resource
    private AfterMarketRepository afterMarketRepository;

    @Resource
    private DataRecycleRepository dataRecycleRepository;

    @Autowired
    private ImgtRepository imgtRepository;

    @Autowired
    private  BoutiqueRepository boutiqueRepository;

    @Autowired
    private PermitCodeRepository permitCodeRepository;


    //分割逗号返回string数组
    public static String[] getStringArr(String str) {
        if (str.contains(",")) {
            String[] arr = str.split(",");
            return arr;
        } else {
            return new String[]{str};
        }
    }

    @Override
    public PageData getProductList(String permit, GetProductListRequest request) {
        request = MoreObjects.firstNonNull(request, new GetProductListRequest());
        PageData page = repository.getProductList(request.getPageSize(), request.getPageIndex(), permit,
                request.type, request.classify, request.source, request.product, request.productCode, request.NC,
                request.area, request.car, request.productID, request.factory,request.totalCount,request.carSource,request.brand,
                request.series,request.carType,request.carParticulars);
        for (Object data : page.getData()) {
            Map map = (Map) data;
            int productID = Integer.parseInt(map.get("精品编号").toString());
            List pics = repository.getProductPic(productID);
            map.put("图片", pics);
            List areas = repository.getProductArea(productID);
            map.put("适用区域", areas);
            List cars = repository.getProductCar(productID);
            map.put("适用车型", cars);
        }

        return page;
    }

    @Override
    public List getProductClassify(int type, String permit) {
        return repository.getProductClassify(type, permit);
    }

    @Override
    public List getProductType(Integer queryType) {
        return repository.getProductType(queryType);
    }

    @Override
    public List getNCType() {
        return repository.getNCType();
    }

    @Override
    public PageData getProductCombo(String permit, GetProductComboRequest request) {
        request = MoreObjects.firstNonNull(request, new GetProductComboRequest());
        PageData page = repository.getProductCombo(request.getPageSize(), request.getPageIndex(), permit, request.comboID, request.comboName, request.area,request.factory, request.createUser,
                request.carSource,request.brand,request.series,request.carType,request.carParticulars);
        for (Object data : page.getData()) {
            Map map = (Map) data;
            int ComboID = Integer.parseInt(map.get("套餐编号").toString());

            List pics = repository.getProductComboPic(ComboID);
            map.put("图片", pics);
            List areas = repository.getProductComboArea(ComboID);
            map.put("适用区域", areas);
            List cars = repository.getProductComboCar(ComboID);
            map.put("适用车型", cars);
        }
        return page;
    }

    @Override
    public List getProductByComboID(int comboID) {
        return repository.getProductByComboID(comboID);
    }

    @Override
    public Map getProduct(int id) {
        //return this.lsh精品信息Repository.findOne(id);
        Map result = repository.getProduct(id);
        if (result != null) {
            List area = repository.getProductArea((int) result.get("精品编号"));
            result.put("适用区域", area);
            List pic = repository.getProductPic((int) result.get("精品编号"));
            result.put("图片", pic);
        }
        return result;
    }

    @Override
    @Transactional
    public Lsh精品信息Model saveProduct(Lsh精品信息Model model) {
        Assert.notNull(model);
        return this.lsh精品信息Repository.save(model);
    }

    @Override
    @Transactional
    public Lsh精品图片Model saveProductImage(InputStream input, String fileName, int id, Integer picId) {
        String path = this.fileRepository.save(input, fileName);
        if (picId != null && picId != 0) {
            Lsh精品图片Model m = lsh精品图片Repository.findOne(picId);
            lsh精品图片Repository.updateById(path, picId);
            return lsh精品图片Repository.findOne(picId);
        }
        Lsh精品图片Model model = new Lsh精品图片Model();
        model.set图片路径(path);
        model.set精品编号(id);
        return this.lsh精品图片Repository.save(model);
    }

    @Override
    @Transactional
    public boolean saveProductStatus(int id, String status) {
        Assert.hasLength(status);
        int result = this.lsh精品信息Repository.set启用状态By精品编号(id, status);
        return true;
    }

    @Override
    public Lsh套餐信息Model getProductCombo(int id) {
        return this.lsh套餐信息Repository.findOne(id);
    }

    @Override
    @Transactional
    public Lsh套餐信息Model saveProductCombo(Lsh套餐信息Model model) {
        Assert.notNull(model);
        return this.lsh套餐信息Repository.save(model);
    }

    @Override
    @Transactional
    public Lsh套餐图片Model saveProductComboImage(InputStream input, String fileName, int id, Integer picId) {
        String path = this.fileRepository.save(input, fileName);
        if (picId != null && picId != 0) {
            Lsh套餐图片Model m = lsh套餐图片Repository.findOne(picId);
            lsh套餐图片Repository.updateById(path, picId);
            Lsh套餐图片Model xx = lsh套餐图片Repository.findOne(picId);
            return lsh套餐图片Repository.findOne(picId);
        }
        Lsh套餐图片Model model = new Lsh套餐图片Model();
        model.set图片路径(path);
        model.set套餐编号(id);
        return this.lsh套餐图片Repository.save(model);
    }

    @Override
    @Transactional
    public boolean saveProductComboStatus(int id, String status) {
        Assert.hasLength(status);
        int result = this.lsh套餐信息Repository.set启用状态By套餐编号(id, status);
        return true;
    }

    @Override
    public PageData getAfterMarketOrder(String permit, GetAfterMarketOrderRequest request) {
        return repository.getAfterMarketOrder(permit, request);
    }

    @Override
    @Transactional
    public 报价单表Model saveOrder(报价单表Model model) {
        Assert.notNull(model);
        return this.报价单表Repository.save(model);
    }

    @Override
    @Transactional
    public List saveOrderProductInfoBatch(List<报价精品详细表精品Model> modelList) {
        //如果 根据 id查出来 有 就是 就是更新，没有 就是 保存   11.11 修改 xxd
        Assert.notNull(modelList);
        List<报价精品详细表精品Model> alll = new ArrayList<>();
        try {
            for (int i = 0; i < modelList.size(); i++) {
                报价精品详细表精品Model m = modelList.get(i);
                报价精品详细表精品Model pk = null;
                if (m.getId() == null) {
                    List<报价精品详细表精品Model> judgeModel =
                            报价精品详细表精品repository.findByThree(m.getProductId(), m.getComboId(), m.get编号());
                    if (judgeModel != null && judgeModel.size() > 0) {
                        报价精品详细表精品Model updateModel = judgeModel.get(0);
                        if (updateModel.getOrderStatus() != null) {
                            pk.setOrderStatus(updateModel.getOrderStatus());
                        }
                        if (updateModel.getContractId() != null) {

                            pk.setContractId(updateModel.getContractId());

                        }
                        if (updateModel.getProductId() != null) {
                            pk.setProductId(updateModel.getProductId());
                        }
                        if (updateModel.getComboId() != null) {
                            pk.setComboId(updateModel.getComboId());
                        }
                        if (updateModel.get编号() != null) {
                            pk.set编号(updateModel.get编号());
                        }

                        if (updateModel.get备注() != null) {
                            pk.set备注(updateModel.get备注());
                        }
                        if (updateModel.get实际施工日期() != null) {
                            pk.set实际施工日期(updateModel.get实际施工日期());
                        }
                        if (updateModel.get预计施工时间() != null) {
                            pk.set预计施工时间(updateModel.get预计施工时间());
                        }
                        if (updateModel.get数量() != null) {
                            pk.set数量(updateModel.get数量());
                        }
                        if (updateModel.get施工种类() != null) {
                            pk.set施工种类(updateModel.get施工种类());
                        }
                        if (updateModel.get申请人() != null) {
                            pk.set申请人(updateModel.get申请人());
                        }

                        if (updateModel.getPurchaseDt() != null) {
                            pk.setPurchaseDt(updateModel.getPurchaseDt());
                        }
                        if (updateModel.getModifyDt() != null) {
                            pk.setModifyDt(updateModel.getModifyDt());
                        }
                        if (updateModel.getRefundDt() != null) {
                            pk.setRefundDt(updateModel.getRefundDt());
                        }
                        if (updateModel.getOrderStatus() != null) {
                            pk.setOrderStatus(updateModel.getOrderStatus());
                        }
                        if (updateModel.getRefundAmount() != null) {
                            pk.setRefundAmount(updateModel.getRefundAmount());
                        }
                        if (updateModel.getRefundReason() != null) {
                            pk.setRefundReason(updateModel.getRefundReason());
                        }
                        if (updateModel.getWip() != null) {
                            pk.setWip(updateModel.getWip());
                        }
                        if (updateModel.getServiceProvider() != null) {
                            pk.setServiceProvider(updateModel.getServiceProvider());
                        }
                        报价精品详细表精品Model resultModel = 报价精品详细表精品repository.save(pk);
                        alll.add(resultModel);
                    } else {
                        报价精品详细表精品Model pks = new 报价精品详细表精品Model();
                        if (m.getOrderStatus() != null) {
                            pks.setOrderStatus(m.getOrderStatus());
                        }

                        if (m.getContractId() != null) {

                            pk.setContractId(m.getContractId());

                        }
                        if (m.getProductId() != null) {
                            pks.setProductId(m.getProductId());
                        }
                        if (m.getComboId() != null) {
                            pks.setComboId(m.getComboId());
                        }
                        if (m.get编号() != null) {
                            pks.set编号(m.get编号());
                        }

                        if (m.get备注() != null) {
                            pks.set备注(m.get备注());
                        }
                        if (m.get实际施工日期() != null) {
                            pks.set实际施工日期(m.get实际施工日期());
                        }
                        if (m.get预计施工时间() != null) {
                            pks.set预计施工时间(m.get预计施工时间());
                        }
                        if (m.get数量() != null) {
                            pks.set数量(m.get数量());
                        }
                        if (m.get施工种类() != null) {
                            pks.set施工种类(m.get施工种类());
                        }
                        if (m.get申请人() != null) {
                            pks.set申请人(m.get申请人());
                        }

                        if (m.getPurchaseDt() != null) {
                            pks.setPurchaseDt(m.getPurchaseDt());
                        }
                        if (m.getModifyDt() != null) {
                            pks.setModifyDt(m.getModifyDt());
                        }
                        if (m.getRefundDt() != null) {
                            pks.setRefundDt(m.getRefundDt());
                        }

                        if (m.getRefundAmount() != null) {
                            pks.setRefundAmount(m.getRefundAmount());
                        }
                        if (m.getRefundReason() != null) {
                            pks.setRefundReason(m.getRefundReason());
                        }

                        if (m.getWip() != null) {
                            pks.setWip(m.getWip());
                        }
                        if (m.getServiceProvider() != null) {
                            pks.setServiceProvider(m.getServiceProvider());
                        }
                        报价精品详细表精品Model resultModels = 报价精品详细表精品repository.save(pks);
                        alll.add(resultModels);

                    }

                } else {

                    pk = 报价精品详细表精品repository.findOne(m.getId());
                    // 如果 传的 本来的 就存在， 那么 就只是 更新

                    if (m.getOrderStatus() != null) {
                        pk.setOrderStatus(m.getOrderStatus());
                    }
                    if (m.getContractId() != null) {

                        pk.setContractId(m.getContractId());

                    }


                    if (m.getProductId() != null) {
                        pk.setProductId(m.getProductId());
                    }
                    if (m.getComboId() != null) {
                        pk.setComboId(m.getComboId());
                    }
                    if (m.get编号() != null) {
                        pk.set编号(m.get编号());
                    }

                    if (m.get备注() != null) {
                        pk.set备注(m.get备注());
                    }
                    if (m.get实际施工日期() != null) {
                        pk.set实际施工日期(m.get实际施工日期());
                    }
                    if (m.get预计施工时间() != null) {
                        pk.set预计施工时间(m.get预计施工时间());
                    }
                    if (m.get数量() != null) {
                        pk.set数量(m.get数量());
                    }
                    if (m.get施工种类() != null) {
                        pk.set施工种类(m.get施工种类());
                    }
                    if (m.get申请人() != null) {
                        pk.set申请人(m.get申请人());
                    }

                    if (m.getPurchaseDt() != null) {
                        pk.setPurchaseDt(m.getPurchaseDt());
                    }
                    if (m.getModifyDt() != null) {
                        pk.setModifyDt(m.getModifyDt());
                    }
                    if (m.getRefundDt() != null) {
                        pk.setRefundDt(m.getRefundDt());
                    }
                    if (m.getOrderStatus() != null) {
                        pk.setOrderStatus(m.getOrderStatus());
                    }
                    if (m.getRefundAmount() != null) {
                        pk.setRefundAmount(m.getRefundAmount());
                    }
                    if (m.getRefundReason() != null) {
                        pk.setRefundReason(m.getRefundReason());
                    }
                    if (m.getWip() != null) {
                        pk.setWip(m.getWip());
                    }
                    if (m.getServiceProvider() != null) {
                        pk.setServiceProvider(m.getServiceProvider());
                    }
                    //更新
                    报价精品详细表精品Model resultUpdateModels = 报价精品详细表精品repository.save(pk);
                    alll.add(resultUpdateModels);
                } // 不为空的 结束
            }//for循坏的 结束


            return alll;


        } catch (Exception e) {
            logger.error("精品保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

        }
        return alll;
    }

    @Override
    public Lsh精品促销Model getPromotionByProductId(int productId, String source) {
        return this.lsh精品促销Repository.findBy精品编号And许可(productId, source);
    }

    @Override
    @Transactional
    public Lsh精品促销Model savePromotion(Lsh精品促销Model model) {
        Assert.notNull(model);
        return this.lsh精品促销Repository.save(model);
    }

    /**
     * 根据精品id获取相关精品信息
     */
    @Override
    public Map findQualityInfoByFuzzyId(Integer id, String source) {
        Map map = repository.findQualityInfoByFuzzyId(id, source);
        if (map != null) {
            map.put("适用区域", repository.getProductArea(id));
            map.put("图片", repository.getProductPic(id));
            map.put("适用车型", repository.getProductCar(id));
        }
        return map;
    }

    /**
     * 保存精品相关信息
     */
    @Override
    @Transactional
    public Map saveQualityInfo(List<GetSaveAfterQualityInfo> reqList) throws ParseException {

        List succQualityInfoIdList = new ArrayList();
        Timestamp tsTime = Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List failList = new ArrayList();
        List succList = new ArrayList();
        int succCount = 0;
        int failCount = 0;
        int succQualityInfoIdCount = 0;
        for (int y = 0; y < reqList.size(); y++) {
            GetSaveAfterQualityInfo req = reqList.get(y);
            java.sql.Date startQuaDate = DateFormatUtils.parseStrToSqlDate(req.精品开始日期);
            java.sql.Date endQuaDate = DateFormatUtils.parseStrToSqlDate(req.精品结束日期);
            Map errorMap = new HashMap();
            //0.需要先判断判断 产品种类，产品分类，产品NC分类是否正确

            //1.根据产品种类，获取种类编号
            Lsh精品种类Model model精品种类 = lsh精品种类Repository.getIdBy产品种类(req.产品种类);
            if (model精品种类 == null) {
                failCount++;
                errorMap.put("errMsg", "产品编号:" + req.产品编号 + " 错误原因:无精品种类信息");
                failList.add(errorMap);
                continue;
            }
            Integer productTypeId = model精品种类.get种类编号();//种类编号

            //2.根据种类编号和产品分类获取分类编号
            Lsh精品分类Model model精品分类 = lsh精品分类Repository.getIdBy种类编号And产品分类(productTypeId, req.产品分类);
            if (model精品分类 == null) {
                failCount++;
                errorMap.put("errMsg", "产品编号:" + req.产品编号 + " 错误原因:无精品分类信息");
                failList.add(errorMap);
                continue;
            }
            Integer lsh分类编号 = model精品分类.get分类编号();

           /* //3.根据nc分类获取nc编号
            Lsh精品Nc分类Model model精品Nc分类 = lsh精品Nc分类Repository.getIdByNc分类(req.nc分类);
            if (model精品Nc分类 == null) {
                failCount++;
                errorMap.put("errMsg", "产品编号:" + req.产品编号 + " 错误原因:无精品NC分类信息");
                failList.add(errorMap);
                continue;
            }
            Integer nc编号 = model精品Nc分类.getNc编号();*/

            //4.更新或者新增到 LSH精品信息
            Lsh精品信息Model e = new Lsh精品信息Model();
            List<Lsh精品信息Model> old精品List = lsh精品信息Repository.findBy产品编号And采购来源(req.采购来源, req.产品编号);
            Lsh精品信息Model old精品 = null;
            if (old精品List.size() > 0) {
                old精品 = old精品List.get(0);
            }
            if (req.精品编号 != null) {
                e.set精品编号(req.精品编号);
            } else {
                if (old精品 != null) {
                    e.set精品编号(old精品.get精品编号());
                }
            }

            //新增：保存精品开始时间和精品结束时间 2017-02-20
            boolean isContinue = false;
            if (e.get精品编号() == null) {
                //如果是新增：直接保存精品开始时间和精品结束时间
                e.set精品开始日期(startQuaDate);
                e.set精品结束日期(endQuaDate);
            } else {
                //如果是更新:
                //1.获取到精品编号,精品套餐，套餐list
                List<Lsh套餐信息Model> arrList = new ArrayList<>();
                List<Lsh精品套餐详细Model> model精品套餐List = lsh精品套餐详细Repository.findDetailRecordByQualityId(e.get精品编号());
                for (int i = 0; i < model精品套餐List.size(); i++) {
                    Lsh精品套餐详细Model model精品套餐 = model精品套餐List.get(i);
                    List<Lsh套餐信息Model> model套餐List = lsh套餐信息Repository.findListById(model精品套餐.get套餐编号(), "是");
                    arrList.addAll(model套餐List);
                }
                //2.遍历套餐list
                for (int i = 0; i < arrList.size(); i++) {
                    Lsh套餐信息Model model套餐信 = arrList.get(i);
                    //如果精品的开始时间<=套餐的开始时间 或 精品的结束时间 >=套餐的结束时间
                    if (startQuaDate.getTime() <= model套餐信.get套餐开始日期().getTime() &&
                            endQuaDate.getTime() >= model套餐信.get套餐结束日期().getTime()) {
                        //暂不做操作
                    } else {
                        //判断是否更新套餐日期
                        if ("是".equals(req.是否更新套餐日期)) {
                            //精品的开始时间 > 套餐的开始时间，更新套餐的开始时间为精品的开始时间
                            if (startQuaDate.getTime() > model套餐信.get套餐开始日期().getTime()) {
                                model套餐信.set套餐开始日期(startQuaDate);
                                lsh套餐信息Repository.save(model套餐信);
                            }
                            //精品的结束时间 < 套餐的结束时间，更新套餐的结束时间为精品的结束时间
                            if (endQuaDate.getTime() < model套餐信.get套餐结束日期().getTime()) {
                                model套餐信.set套餐结束日期(endQuaDate);
                                lsh套餐信息Repository.save(model套餐信);
                            }
                        } else {
                            //否，跳过当前
                            isContinue = true;
                            break;
                        }
                    }
                }
            }
            if (isContinue == true) {
                errorMap.put("errMsg", "产品编号:" + req.产品编号 + " 错误原因:该精品导入有效期与所属套餐有效期冲突");
                failCount++;
                failList.add(errorMap);
                continue;
            }
            if (Strings.isNullOrEmpty(req.厂商)){
                errorMap.put("errMsg","错误原因:厂商不能为空");
                failCount++;
                failList.add(errorMap);
                continue;
            }
            if (Strings.isNullOrEmpty(req.经销商销售价含税)){
                errorMap.put("errMsg","错误原因:经销商销售价含税不能为空");
                failCount++;
                failList.add(errorMap);
                continue;
            }
            e.set精品开始日期(startQuaDate);
            e.set精品结束日期(endQuaDate);
            e.set分类编号(lsh分类编号);
            e.set采购来源(req.采购来源);
            //e.setNc编号(nc编号);
            e.set产品编号(req.产品编号);
            e.set产品名称(req.产品名称);
            e.set厂商(req.厂商);
            e.set标配功能(req.标配功能);
            e.set经销商采购价含税(req.经销商采购价含税);
            e.set经销商采购价未税(req.经销商采购价未税);
            e.set经销商采购毛利未税(req.经销商采购毛利未税);
            e.set集团采购价含税(req.集团采购价含税);
            e.set集团采购毛利率(req.集团采购毛利率);
            e.set集团采购价未税(req.集团采购价未税);
            e.set经销商销售价含税(req.经销商销售价含税);
            e.set经销商销售价未税(req.经销商销售价未税);
            e.set经销商销售毛利率未税(req.经销商销售毛利率未税);
            e.set单品促销状态(req.单品促销状态);
            e.set启用状态(req.启用状态);
            e.set特征(req.特征);
            e.set功能(req.功能);
            e.set好处(req.好处);
            e.set更新账号(req.更新账号);
            e.set创建时间(req.创建时间);
            e.set更新时间(tsTime);
            Lsh精品信息Model model精品信息 = lsh精品信息Repository.save(e);
            Integer qualityInfoId = model精品信息.get精品编号();//精品编号

            //5.保存精品促销信息
            Lsh精品促销Model model精品促销 = new Lsh精品促销Model();
            Lsh精品促销Model old精品促销 = lsh精品促销Repository.findBy许可And精品编号(qualityInfoId, req.采购来源);
            if (old精品促销 != null) {
                model精品促销.set精品促销编号(old精品促销.get精品促销编号());
            }

            model精品促销.set精品编号(qualityInfoId);
            model精品促销.set许可(e.get采购来源());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (!"0000-00-00 00:00:00".equals(req.促销开始日期)) {
                Date startDate = sdf.parse(req.促销开始日期);
                model精品促销.set促销开始日期(startDate);
            }
            if (!"0000-00-00 00:00:00".equals(req.促销结束日期)) {
                Date endDate = sdf.parse(req.促销结束日期);
                model精品促销.set促销结束日期(endDate);
            }
            model精品促销.set经销商采购价未税(req.经销商采购价未税促销);
            model精品促销.set经销商采购价含税(req.经销商采购价含税促销);
            model精品促销.set经销商采购折扣率(req.经销商采购折扣率促销);
            model精品促销.set经销商销售价含税(req.经销商销售价含税促销);
            model精品促销.set经销商销售价未税(req.经销商销售价未税促销);
            model精品促销.set经销商销售折扣率(req.经销商销售折扣率促销);
            model精品促销.set更新账号(req.更新账号);
            model精品促销.set更新时间(tsTime);
            Lsh精品促销Model new精品促销 = lsh精品促销Repository.save(model精品促销);

            //6.保存 LSH精品适用车型
            List<Lsh精品适用车型Model> carList = lsh精品适用车型Repository.findCarRecordByQualityId(qualityInfoId);
            if (carList.size() > 0) {
                //6.1如果数据存在，需要先将数据删除
                lsh精品适用车型Repository.delete(carList);
            }
            //6.2新增
            String[] arr车型编号 = getStringArr(req.适用车型编号);
            for (int i = 0; i < arr车型编号.length; i++) {
                Lsh精品适用车型Model m = new Lsh精品适用车型Model();
                m.set精品编号(qualityInfoId);
                m.set车型编号(Integer.valueOf(arr车型编号[i]));
                Lsh精品适用车型Model newRecord = lsh精品适用车型Repository.save(m);
            }

            //7.保存 LSH精品适用区域
            List<Lsh精品适用区域Model> areaList = lsh精品适用区域Repository.findAreaRecordByQualityId(qualityInfoId);
            if (areaList.size() > 0) {
                //7.1如果数据存在，需要先将数据删除
                lsh精品适用区域Repository.delete(areaList);
            }
            //7.2 新增
            if (req.适用区域 != null) {
                String[] arr适用区域 = getStringArr(req.适用区域);
                for (int j = 0; j < arr适用区域.length; j++) {
                    Lsh精品适用区域Model n = new Lsh精品适用区域Model();
                    n.set精品编号(qualityInfoId);
                    n.set适用区域(arr适用区域[j]);
                    Lsh精品适用区域Model newAreaRecord = lsh精品适用区域Repository.save(n);
                }
            }


        /* 保存/更新精品信息的同时，需要向 LSH套餐信息 中新增/更新 同样的数据（分类编号，
         创建房，NC分类，产品编号，产品名称，更新账号，更新时间，启用状态），多余数据可以为空，
         需要注意将LSH套餐信息 表中的 `是否套餐`设置为否。
         同时将此套餐和精品在 LSH精品套餐详细中关联起来，LSH精品套餐详细中，
         精品折扣为 100，精品数量为1。
         */
            //8.如果是新增数据
            if (req.精品编号 == null &&old精品==null) {
                // 8.1新增LSH套餐信息
                Lsh套餐信息Model model套餐信息 = new Lsh套餐信息Model();
                model套餐信息.set分类编号(lsh分类编号);
                //创建方=lsh精品信息的采购来源,如果采购来源是TJLS，则创建方=RMB，如果不是，则是其他
                if ("TJLS".equals(req.采购来源)) {
                    model套餐信息.set创建方("RMB");
                } else {
                    model套餐信息.set创建方(req.采购来源);
                }
                //model套餐信息.setNc编号(nc编号);
                model套餐信息.set产品编号(req.产品编号);
                model套餐信息.set产品名称(req.产品名称);
                model套餐信息.set是否套餐("否");
                model套餐信息.set启用状态("启用");
                model套餐信息.set更新时间(tsTime);
                model套餐信息.set更新账号(req.更新账号);
                model套餐信息.set限量状态("无限量");
                Lsh套餐信息Model new套餐信息 = lsh套餐信息Repository.save(model套餐信息);
                // 8.2 新增/更新Lsh精品套餐详细
                Lsh精品套餐详细Model new精品套餐详细Model = new Lsh精品套餐详细Model();
                new精品套餐详细Model.set套餐编号(new套餐信息.get套餐编号());
                new精品套餐详细Model.set精品编号(qualityInfoId);
                new精品套餐详细Model.set精品折扣(100.00);
                new精品套餐详细Model.set精品数量("1");
                new精品套餐详细Model.set更新账号(req.更新账号);
                new精品套餐详细Model.set更新时间(tsTime);
                lsh精品套餐详细Repository.save(new精品套餐详细Model);

            } else {
                List<Lsh精品套餐详细Model> model精品套餐详细List=null;
                if(old精品!=null&&old精品.get精品编号()!=null){
                    model精品套餐详细List = lsh精品套餐详细Repository.findDetailRecordByQualityId(old精品.get精品编号());
                }else if (req.精品编号!=null){
                    model精品套餐详细List = lsh精品套餐详细Repository.findDetailRecordByQualityId(req.精品编号);
                }
                //9.如果是更新数据
                //9.1 通过精品编号查询Lsh精品套餐详细，得到套餐编号list


                // 9.2 根据获得的套餐编号list查询Lsh套餐信息，得到套餐信息List,但是只有一条的套餐是“否”
                Lsh套餐信息Model entity = null;
                for (int n = 0; n < model精品套餐详细List.size(); n++) {
                    entity = lsh套餐信息Repository.findOne(model精品套餐详细List.get(n).get套餐编号());
                    if ("否".equals(entity.get是否套餐())) {
                        break;
                    }
                }
                //9.3更新Lsh套餐信息
                entity.set分类编号(lsh分类编号);
                //entity.setNc编号(nc编号);
                entity.set产品名称(req.产品名称);
                entity.set更新账号(req.更新账号);
                entity.set更新时间(tsTime);
                lsh套餐信息Repository.save(entity);
            }
            succQualityInfoIdList.add(qualityInfoId);
            succQualityInfoIdCount++;
            succList.add(req.产品编号);
            succCount++;
        }
        Map map = new HashMap();
        map.put("succList", succList);
        map.put("succCount", succCount);
        map.put("failList", failList);
        map.put("failCount", failCount);
        map.put("succQualityInfoIdList", succQualityInfoIdList);
        map.put("succQualityInfoIdCount", succQualityInfoIdCount);
        return map;
    }

    /**
     * 根据产品编号和采购来源判断精品是否存在
     */
    @Override
    public boolean isExistQualityInfo(String productNum, String source) {
        List list = repository.isExistQualityInfo(productNum, source);
        if (list.size() == 0 || list == null) {
            return false;
        }
        return true;
    }

    /**
     * 根据 套餐编号 获取 后市场套餐信息，精品适用车型，精品图片
     */
    @Override
    public Map findComboInfoByProductNumAndUser(String productNum, String createUser) {
        Map map = repository.findComboInfoByProductNumAndUser(productNum, createUser);
        if (map != null) {
            int ComboID = Integer.parseInt(map.get("套餐编号").toString());
            List pics = repository.getProductComboPic(ComboID);
            map.put("图片", pics);
            List areas = repository.getProductComboArea(ComboID);
            map.put("适用区域", areas);
            List cars = repository.getProductComboCar(ComboID);
            map.put("适用车型", cars);
        }
        return map;
    }

    /**
     * 根据 套餐编号 获取 精品信息
     */
    @Override
    public List findQualityInfoByComboId(Integer comboId) {
        return repository.findQualityInfoByComboId(comboId);
    }

    /**
     * 获取大小区域
     */
    @Override
    public List getAllArea() {
        List areaList = new ArrayList();
        List list = repository.getAllArea();
        for (int i = 0; i < list.size(); i++) {
            Map areaMap = new HashMap();
            Map map = (Map) list.get(i);
            areaMap.put("region", map.get("区域"));
            areaMap.put("regionCode", map.get("区域_EN"));
            areaList.add(areaMap);
        }
        return areaList;
    }

    /**
     * 根据产品编号和采购来源获取精品信息
     */
    @Override
    public Map findQualityInfoByProductNumAndSource(String productNum, String source) {
        Map map = repository.findQualityInfoByProductNumAndSource(productNum, source);
        if (map != null) {
            Integer id = Integer.valueOf(map.get("精品编号").toString());
            map.put("适用区域", repository.getProductArea(id));
            map.put("图片", repository.getProductPic(id));
            map.put("适用车型", repository.getProductCar(id));
        }
        return map;
    }

    /**
     * 保存套餐相关信息
     */
    @Override
    @Transactional
    public List saveComboInfo(GetSaveComboInfo req) {
        List list = new ArrayList();
        //1.更新或者保存套餐信息表
        Lsh套餐信息Model entity = new Lsh套餐信息Model();
        entity.set套餐编号(req.套餐编号);
        entity.set创建方(req.创建方);
        entity.set产品编号(req.产品编号);
        entity.set产品名称(req.产品名称);
        entity.set套餐开始日期(req.套餐开始日期);
        entity.set套餐结束日期(req.套餐结束日期);
        entity.set限量状态(req.限量状态);
        entity.set限量数量(req.限量数量);
        entity.set套餐销售原价(req.套餐销售原价);
        entity.set套餐销售价含税(req.套餐销售价含税);
        entity.set是否统一折扣(req.是否统一折扣);
        entity.set套餐折扣(req.套餐折扣);
        entity.set套餐采购价含税(req.套餐采购价含税);
        entity.set套餐毛利(req.套餐毛利);
        entity.set套餐毛利率(req.套餐毛利率);
        entity.set是否套餐("是");
        entity.set功能(req.功能);
        entity.set特征(req.特征);
        entity.set好处(req.好处);
        entity.set启用状态(req.启用状态);
        entity.set更新账号(req.更新账号);
        entity.set创建时间(req.创建时间);
        Lsh套餐信息Model model = lsh套餐信息Repository.save(entity);
        list.add(model);
        Integer comboId = model.get套餐编号();//套餐编号
        //2.保存 LSH套餐适用车型
        List<Lsh套餐适用车型Model> carList = lsh套餐适用车型Repository.findCarRecordByComboId(comboId);
        if (carList.size() > 0) {
            //2.1如果数据存在，需要先将数据删除
            lsh套餐适用车型Repository.delete(carList);
        }
        //2.2新增
        String[] arr车型编号 = getStringArr(req.适用车型编号);
        for (int i = 0; i < arr车型编号.length; i++) {
            Lsh套餐适用车型Model m = new Lsh套餐适用车型Model();
            m.set套餐编号(comboId);
            m.set车型编号(Integer.valueOf(arr车型编号[i]));
            Lsh套餐适用车型Model newRecord = lsh套餐适用车型Repository.save(m);
            list.add(newRecord);
        }
        //3.保存 LSH套餐适用区域，需要先将数据删除
        List<Lsh套餐适用区域Model> areaList = lsh套餐适用区域Repository.findAreaRecordByComboId(comboId);
        if (areaList.size() > 0) {
            //3.1如果数据存在，需要先将数据删除
            lsh套餐适用区域Repository.delete(areaList);
        }
        //3.2 新增
        if (req.适用区域 != null) {
            String[] arr适用区域 = getStringArr(req.适用区域);
            for (int j = 0; j < arr适用区域.length; j++) {
                Lsh套餐适用区域Model n = new Lsh套餐适用区域Model();
                n.set套餐编号(comboId);
                n.set适用区域(arr适用区域[j]);
                Lsh套餐适用区域Model newAreaRecord = lsh套餐适用区域Repository.save(n);
                list.add(newAreaRecord);
            }
        }

        //4.保存 LSH精品套餐详细
        if (req.list != null && req.list.size() > 0) {
            List<Lsh精品套餐详细Model> oldlist = lsh精品套餐详细Repository.findDetailRecordByComboId(comboId);

            if (oldlist.size() > 0) {
                //4.1 如果数据存在,需要先将数据删除
                lsh精品套餐详细Repository.delete(oldlist);
            }
            //4.2 新增
            List<Lsh精品套餐详细Model> detailList = req.list;
            for (int k = 0; k < detailList.size(); k++) {
                detailList.get(k).set套餐编号(comboId);
                Lsh精品套餐详细Model newDetai = lsh精品套餐详细Repository.save(detailList.get(k));
                list.add(newDetai);
            }
        }

        return list;
    }

    /**
     * 根据产品编号和创建方判断套餐是否存在
     */
    @Override
    public boolean isExistComboInfo(String productNum, String createUser) {
        List list = repository.isExistComboInfo(productNum, createUser);
        return list.size() > 0 ? true : false;
    }

    /**
     * 获取随车项目信息
     */
    @Override
    public List getFollowCarInfoByPermit(String permit) {
        return repository.getFollowCarInfoByPermit(permit);
    }

    /**
     * 保存随车项目设置
     */
    @Override
    @Transactional
    public boolean saveFollowCarInfoList(List<Lsh随车项目设置Model> reqList) {
        try {
            lsh随车项目设置repository.save(reqList);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("随车项目设置导入功能异常", e);
            return false;
        }
        return true;
    }

    @Override
    public List getAllQualityInfoBySource(String source) {
        return repository.getAllQualityInfoBySource(source);
    }

    @Override
    public boolean isExistfallowCar(IsExistfallowCarRequest req) {
        List list = repository.isExistfallowCar(req.permit, req.启用时间, req.停用时间, req.车型编号, req.项目成本编号);
        return list.size() > 0 ? true : false;
    }


    // 根据精品编号 id 获取 到精品的 详细信息
    @Override
    public Lsh精品信息Model getAfterMarketOrdersProductById(String productId) {
        int productIds = Integer.parseInt(productId);
        return lsh精品信息Repository.findBy精品编号productId(productIds);
    }





    // 录入的 是 退货金额和 退货理由  涉及 表： 报价精品详细表_精品  也会 影响我们的 订单状态
    @Override
    @Transactional
    public boolean saveRefoundAfterMarketOrderProductDetail(getRefoundAfterMarketOrderProductDetail re) {
        boolean flag = false;
        try {

            if (re.ids != null && !"".equals(re.ids)) {
                报价精品详细表精品Model vms = 报价精品详细表精品repository.findOne(re.ids);
                /////
                vms.setOrderStatus(re.status);

                Date dssss = new Date();
                Timestamp ts = new Timestamp(dssss.getTime());
                vms.setRefundDt(ts);
                if (re.refoundMoney != null && !re.refoundMoney.equals("")) {
                    vms.setRefundAmount(re.refoundMoney);
                }
                if (re.reason != null && !"".equals(re.reason)) {
                    vms.setRefundReason(re.reason);
                }

                报价精品详细表精品repository.save(vms);


            } else {
              // 如果  传入的 id为空 那么 直接 就是 插入    以前的 联合主键 不能为空
                报价精品详细表精品Model vm = new 报价精品详细表精品Model();
                if (re.productId != 0 && re.productId != null && !"".equals(re.productId)) {
                    vm.setProductId(re.productId);
                }
                if (re.conid != 0 && re.conid != null && !"".equals(re.productId)) {
                    vm.setComboId(re.conid);
                }
                if (re.bianhao != 0 && re.bianhao != null && !"".equals(re.conid)) {
                    vm.set编号(re.bianhao);
                }
                if (re.status != null && !"".equals(re.status)) {
                    vm.setOrderStatus(re.status);
                }
                if (re.refoundMoney != null && !"".equals(re.refoundMoney)) {
                    vm.setRefundAmount(re.refoundMoney);
                }
                if (re.reason != null) {
                    vm.setRefundReason(re.reason);
                }
                Date dssss = new Date();
                Timestamp ts = new Timestamp(dssss.getTime());
                vm.setRefundDt(ts);
                报价精品详细表精品repository.save(vm);
            }
             //退换货需要后处理 ，给天津利星发消息



            flag = true;
        } catch (Exception e) {
            logger.error("保存套餐信息失败", e);
            flag = false;

        }
        return flag;
    }

    // 获取的 是 精品的 分类 和具体的信息
    @Override
    public PageData getAfterMarketProductTypeAndDetail(getAfterMarketProductTypeAndDetail request) {
        return repository.getAfterMarketProductTypeAndDetail(request.getPageIndex(), request.getPageSize(), request.type);
    }


    // 11.9    18.34 新加一个 提交 订单后  发送消息的 接口    11.11 修改 xxd
    @Override
    @Transactional
    public PageData saveOederstatusAndmsg(List<getOederstatusAndmsg> requestlist, String permit, String postuser) {

        List suceeList = new ArrayList();
        List failList = new ArrayList();
        try {
            // 如果 传的 id 查不出 对应的 model 那么 就 直接 放入 放入 faillist
            for (int i = 0; i < requestlist.size(); i++) {
                getOederstatusAndmsg ss = requestlist.get(i);

                if ("".equals(ss.id) || ss.id == 0) {

                    报价精品详细表精品Model olds5 = new 报价精品详细表精品Model();
                    olds5.setProductId(ss.productId);
                    olds5.setComboId(ss.conid);
                    olds5.set编号(ss.bianhao);
                    olds5.set数量(ss.sums);
                    olds5.setOrderStatus("2");     // 没有实现主键自增
                    Date dssss = new Date();
                    Timestamp ts = new Timestamp(dssss.getTime());
                    olds5.setPurchaseDt(ts);
                    olds5.set申请人(postuser);

                    报价精品详细表精品Model olds5s = 报价精品详细表精品repository.save(olds5);
                    suceeList.add(olds5s);

                } else {
                    报价精品详细表精品Model olds4 = 报价精品详细表精品repository.findOne(ss.id);

                    if (olds4 != null) {           // 不为空
                        String status = olds4.getOrderStatus();
                        if (status != null) { //  当状态 不为null   因为 0.9 版本的 数据库 中 status 肯定是 null 需要 兼容
                            int os = Integer.parseInt(status);
                            if (os == 1 || os == 5 || os == 9) {
                                String nowupdate = String.valueOf(os + 1);
                                olds4.setOrderStatus(nowupdate);
                                if (olds4.getPurchaseDt() == null) {
                                    // 为空 就是 赋值  不为空 已经采购 11.14 xxd
                                    Date dssss = new Date();
                                    Timestamp ts = new Timestamp(dssss.getTime());
                                    olds4.setPurchaseDt(ts);

                                }
                                olds4.set申请人(postuser);
                                报价精品详细表精品Model olds4u = 报价精品详细表精品repository.save(olds4);
                                suceeList.add(olds4u);
                            } else {
                                failList.add(olds4);
                            }

                        } else {
                            // 考虑到 0.9 的 _精品 里面的 状态 全部是 null ， 可能会导致 所有的失败，
                            // 于是 orderStatus = null 更改为 1
                            //  实际 它 本来 的null 代表 1， 由于 他是一直存在，只是版本原因，所以 需要 更改为 是2
                            String nowupdates = "2";
                            olds4.setOrderStatus(nowupdates);
                            if (olds4.getPurchaseDt() == null) {
                                // 为空 就是 赋值  不为空 已经采购 11.14 xxd
                                Date dssss = new Date();
                                Timestamp ts = new Timestamp(dssss.getTime());
                                olds4.setPurchaseDt(ts);
                            }
                            olds4.set申请人(postuser);
                            报价精品详细表精品Model olds4uff = 报价精品详细表精品repository.save(olds4);
                            suceeList.add(olds4uff);
                            // failList.add(olds4);
                        }


                    } else {
                        //如果 查不到 任何 数据 ， 那么  传过来的 到 _精品 表  不保存
                        报价精品详细表精品Model olds4s = new 报价精品详细表精品Model();
                        olds4s.setId(ss.id);
                        // 报价精品详细表精品Model olds4udsss = 报价精品详细表精品repository.save(olds4s);
                        failList.add(olds4s);
                    }


                }
            }
            // 如果 是  succesList有，而且 是 user 也存在  于是 就会发消息
            List userlist = repository.getuserMessages();
            if (suceeList.size() > 0 && userlist.size() > 0) {
                //messageSettingRepository
                String content = MessageContext.postAfterMarketOrder(permit);
                LshMsgUtils.getLshMsg(permit, postuser, permit, userlist.get(0).toString(), "后市场", content, postuser, null);
            }

        } catch (Exception e) {
            logger.error("保存后市场订单信息失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


        PageData pg = new PageData(failList, failList.size());
        return pg;
    }


    /**
     * 逻辑 是
     * 首先根据 编号 查到 报价精品表  更新掉
     * 11.10  晚上18:01
     * 然后根据 编号+
     */
    @Override
    @Transactional
    public boolean saveAddafterMarketOrdersAndallupdate(List<getAddafterMarketOrdersAndallupdate> requestlist, String permit, String postuser, String baojiabianhao) {

        boolean flag = true;
        try {

            /***
             * 如果 baojiabianhao  》》 编号id为  null： 创建 报价精品表
             * 不为null 更新 报价单表 精品=id and 编号=？
             * */
            if (baojiabianhao == null || "".equals(baojiabianhao)) {
                return false;

            } else {
                /*** 根据 baojiabianhao 拿到 编号
                 如果 说 编号 为 null 那么 直接 创建 报价精品详细表 就是 for 里面的 所有的 sum 然后拿到 编号
                 如果 不null  更新 报价单表 的 精品id   +
                 还把 编号+ （套餐编号+-》 comid）-》 报价精品详细表
                 null 则 新增
                 */
                int trueid = Integer.parseInt(baojiabianhao);
                报价单表Model bmd = 报价单表Repository.findBy报价编号(trueid);
                if (bmd != null) {
                    if (bmd.get精品() != null && !"".equals(bmd.get精品())) {

                        // 不为空时，
                        //也需要 更新 报价精品表
                        BigDecimal sumsdm1 = new BigDecimal(0);
                        BigDecimal sumsdm2 = new BigDecimal(0);
                        BigDecimal sumsdm3 = new BigDecimal(0);
                        报价精品表Model zhenzhengmodel = 报价精品表Repository.findby编号(bmd.get精品());

                        for (int ij = 0; ij < requestlist.size(); ij++) {
                            getAddafterMarketOrdersAndallupdate gsss = requestlist.get(ij);
                            sumsdm1 = sumsdm1.add(gsss.shoujia);
                            sumsdm2 = sumsdm2.add(gsss.shoujia);
                            if (gsss.issuiche.equals("是")) {
                                sumsdm3 = sumsdm3.add(gsss.chengben);
                            }

                        }// for 循坏结束
                        // 然后 直接 保存 一个  报价精品表

                        zhenzhengmodel.set精品折后价(sumsdm1.add(zhenzhengmodel.get精品折后价()));
                        zhenzhengmodel.set精品原价(sumsdm2.add(zhenzhengmodel.get精品原价()));

                        zhenzhengmodel.set精品成本(sumsdm3.add(zhenzhengmodel.get精品成本()));
                        Date dssss = new Date();
                        Timestamp ts = new Timestamp(dssss.getTime());
                        zhenzhengmodel.set更新时间(ts);
                        zhenzhengmodel.set更新账号(postuser);
                        // 实现 插入 保存之后 就会 拿到 一个 新建的 增的 新id
                        报价精品表Repository.save(zhenzhengmodel);
                        // 如果 精品id ----编号 不为空
                        int xinids = bmd.get精品();
                        for (int ij = 0; ij < requestlist.size(); ij++) {
                            getAddafterMarketOrdersAndallupdate gssy = requestlist.get(ij);
                            // 然后拿到 comid  如果有那么就更新，没有则 是插入
                            // 根据 productId 拿到 lsh套餐信息的 套餐编号
                            //  ssd 肯定只有 一条
                            List ssd = repository.findDetailtaocangDetailBytwoId(gssy.productId);
                            // 这是 后续操作
                            flag = jingxingNullToInsertAndhouxian(ssd, permit, postuser, xinids, gssy);
                        }

                    } else { // 如果 为空 则 把 报价精品表 he 报价精品详细表  实现插入
                        BigDecimal sumsdm4 = new BigDecimal(0);
                        BigDecimal sumsdm6 = new BigDecimal(0);
                        BigDecimal sumsdm5 = new BigDecimal(0);


                        for (int ij = 0; ij < requestlist.size(); ij++) {
                            getAddafterMarketOrdersAndallupdate gsss = requestlist.get(ij);
                            sumsdm4 = sumsdm4.add(gsss.shoujia);
                            sumsdm6 = sumsdm6.add(gsss.shoujia);
                            if (gsss.issuiche.equals("是")) {
                                sumsdm5 = sumsdm5.add(gsss.chengben);
                            }
                        }// for 循坏结束
                        // 然后 直接 保存 一个  报价精品表
                        报价精品表Model bamamodels = new 报价精品表Model();
                        bamamodels.set精品折后价(sumsdm4);
                        bamamodels.set精品原价(sumsdm6);
                        bamamodels.set精品成本(sumsdm5);

                        Date dssss = new Date();
                        Timestamp ts = new Timestamp(dssss.getTime());
                        bamamodels.set更新时间(ts);
                        bamamodels.set更新账号(postuser);
                        // 实现 插入 保存之后 就会 拿到 一个 新建的 增的 新id
                        报价精品表Model zhenzhengmodel = 报价精品表Repository.save(bamamodels);

                        int xinids = zhenzhengmodel.get编号();
                        // 拿到 编号 后 更改 之前的 报价单表 的  精品 状态
                        bmd.set精品(xinids);
                        报价单表Repository.save(bmd);

                        // 这时候 就是 for 里面的 productId 发挥作用
                        for (int ij = 0; ij < requestlist.size(); ij++) {

                            getAddafterMarketOrdersAndallupdate gssy = requestlist.get(ij);
                            // 然后拿到 comid  如果有那么就更新，没有则 是插入
                            // 根据 productId 拿到 lsh套餐信息的 套餐编号
                            //  ssd 肯定只有 一条
                            List ssd = repository.findDetailtaocangDetailBytwoId(gssy.productId);
                            // 这是 后续操作
                            flag = jingxingNullToInsertAndhouxian(ssd, permit, postuser, xinids, gssy);
                        }  // 以上就是 新插入的 东西 得到的 编号 --》 然后 实现 的 查到的 报价精品详细表 （null 新增 + 更新） 的 for的 结束
                    }// 精品id 为空的 结束

                }// model不为空 的 if结束

            }//baojiabianhao！=null的 情况

        } catch (Exception e) {
            logger.error("lsh套餐信息详细保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        }

        return flag;
    }


    @Transactional
    private boolean jingxingNullToInsertAndhouxian(List ssd, String permit, String postuser, int bianhao, getAddafterMarketOrdersAndallupdate item) {
        boolean flag = false;
        try {
// 然后拿到 comid  如果有那么就更新，没有则 是插入
            // 根据 productId 拿到 lsh套餐信息的 套餐编号
            报价精品表Model models = 报价精品表Repository.findby编号(bianhao);
            if (ssd.size() > 0) {
                Map sms = (Map) ssd.get(0);
                int comid = Integer.parseInt(sms.get("套餐编号").toString()); //   套餐编号();
                // 根据 comid 和编号 拿到  报价精品详细表 有则更新， 无则 插入
                报价精品详细表Model baojialist = 报价精品详细表Repository.findDetailRecordByComboIdsss(bianhao, comid);
                if (baojialist != null) {
                    // 有则更新
                    baojialist.set更新账号(postuser);
                    Date dsssss = new Date();
                    Timestamp tss = new Timestamp(dsssss.getTime());
                    baojialist.set更新时间(tss);

                    if (baojialist.get成本() == null || "".equals(baojialist.get成本())) {
                        baojialist.set成本(item.chengben);
                    } else {
                        BigDecimal yuanjias6 = baojialist.get成本();
                        baojialist.set成本(item.chengben.add(yuanjias6));
                    }

                    if (baojialist.get数量() == null || "".equals(baojialist.get数量())) {
                        baojialist.set数量(item.shuliang);
                    } else {
                        int yuanjias7 = baojialist.get数量();
                        baojialist.set数量(item.shuliang + yuanjias7);
                    }

                    if (baojialist.get原价() == null || "".equals(baojialist.get原价())) {
                        baojialist.set原价(item.shoujia);
                    } else {
                        BigDecimal yuanjias9 = baojialist.get原价();
                        baojialist.set原价(item.shoujia.add(yuanjias9));
                    }
                    if (baojialist.get折后价() == null || "".equals(baojialist.get折后价())) {
                        baojialist.set折后价(item.shoujia);
                    } else {
                        BigDecimal yuanjias10 = baojialist.get折后价();
                        baojialist.set折后价(item.shoujia.add(yuanjias10));
                    }

                   /* baojialist.set成本(baojialist.get成本().add(gss.chengben));
                    baojialist.set数量(baojialist.get数量()+gss.shuliang);

                    baojialist.set原价(baojialist.get原价().add(gss.shoujia));*/
                    报价精品详细表Repository.save(baojialist);

                    // 保存 _精品 表
                    报价精品详细表精品Model baojingpings = new 报价精品详细表精品Model();

                    baojingpings.set编号(bianhao);
                    baojingpings.setComboId(comid);
                    baojingpings.setOrderStatus("1");
                    baojingpings.setProductId(Integer.parseInt(item.productId));
                    baojingpings.set数量(item.shuliang);
                    报价精品详细表精品repository.save(baojingpings);

                } else {
                    // 没有 就是 插入 并且 更新 _精品表
                    报价精品详细表Model baojialists = new 报价精品详细表Model();
                    Date dsssss = new Date();
                    Timestamp tss = new Timestamp(dsssss.getTime());
                    baojialists.set更新账号(postuser);
                    baojialists.set更新时间(tss);
                    baojialists.set成本(item.chengben);
                    baojialists.set数量(item.shuliang);
                    baojialists.set编号(bianhao);
                    baojialists.setId(comid);
                    baojialists.set原价(item.shoujia);
                    baojialists.set名称(item.mingcheng);
                    baojialists.set折后价(item.shoujia);
                    报价精品详细表Repository.save(baojialists);

                    //而且 还需要把 _精品也插入
                    报价精品详细表精品Model baojingping = new 报价精品详细表精品Model();

                    baojingping.set编号(bianhao);
                    baojingping.setComboId(comid);
                    baojingping.setOrderStatus("1");
                    baojingping.setProductId(Integer.parseInt(item.productId));
                    baojingping.set数量(item.shuliang);
                    报价精品详细表精品repository.save(baojingping);

                }

            }// 这是 Lsh精品套餐详细Model的list>0 的借宿
            flag = true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("精品_精品表插入出错", e);
            flag = false;
        }
        return flag;
    }

    // 新增的 接口 Map getdingdanbianhao(String ids);  得到 报价编号
    @Override
    public Map getdingdanbianhao(String ids, String permit) {

        return repository.getdingdanbianhao(ids, permit);

    }


    // 11.11 的  更改状态
    @Transactional
    public PageData saveOrderStatusAndbaocun(List<getOrderStatusAndBaocun> requestlist) {
        List faillist = new ArrayList();
        List sucllist = new ArrayList();
        for (int i = 0; i < requestlist.size(); i++) {
            getOrderStatusAndBaocun sdsss = requestlist.get(i);
            报价精品详细表精品Model bmg = 报价精品详细表精品repository.findOne(sdsss.id);
            try {
                if (bmg != null && !"".equals(bmg)) {
                    bmg.setOrderStatus(sdsss.orderStatus);
                    报价精品详细表精品Model bmgs = 报价精品详细表精品repository.save(bmg);
                    sucllist.add(bmgs);
                } else {
                    报价精品详细表精品Model bmgsb = new 报价精品详细表精品Model();
                    bmgsb.setId(sdsss.id);
                    bmgsb.setOrderStatus(sdsss.orderStatus);
                    报价精品详细表精品Model bmgsbs = 报价精品详细表精品repository.save(bmgsb);
                    faillist.add(bmgsbs);
                }

            } catch (Exception e) {
                logger.error("详细表精品保存失败", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

        }
        List lili = new ArrayList();
        lili.add(faillist);
        lili.add(sucllist);
        PageData pgs = new PageData(faillist, faillist.size());

        return pgs;

    }


    /***
     *查询待该店开票金额的总金额，和所获取的精品id列表
     *
     * 传入 的 trueId
     * */
    @Override
    public List getAfterMarketShopAllId(String ids) {

        return repository.getAfterMarketShopAllId(ids);

    }


    //批量保存 所有的  录入的 经销商的开票的信息
    @Transactional
    public boolean saveBusinesstickets(List<getBusinesstickets> lblist) {
        boolean flag = false;
        try {

            for (int i = 0; i < lblist.size(); i++) {
                getBusinesstickets gla = lblist.get(i);
                if (gla.btId != null) { // trueId 不为空

                    // 对应的 有  表中的行              用 税号 去查   直接更新
                    BusinessticketsModel bmd = businessticketsRepositorys.getBmodelById(gla.btId);
                    if (!"".equals(gla.btAddrAndTel) && gla.btAddrAndTel != null) {
                        bmd.setBtAddrAndTel(gla.btAddrAndTel);  // 修改 不改动 启动状态
                    } else {
                        bmd.setBtAddrAndTel(null);
                    }

                    if (!"".equals(gla.firstreviewPerson) && gla.firstreviewPerson != null) {
                        bmd.setFirstreviewPerson(gla.firstreviewPerson);  // 修改 不改动 启动状态
                    } else {
                        bmd.setFirstreviewPerson(null);
                    }
                    if (!"".equals(gla.endreviewPerson) && gla.endreviewPerson != null) {
                        bmd.setEndreviewPerson(gla.endreviewPerson);  // 修改 不改动 启动状态
                    } else {
                        bmd.setEndreviewPerson(null);
                    }

                    if (!"".equals(gla.btBankAccount) && gla.btBankAccount != null) {
                        bmd.setBtBankAccount(gla.btBankAccount);  // 修改 不改动 启动状态
                    } else {
                        bmd.setBtBankAccount(null);
                    }

                    if (!"".equals(gla.btLogo) && gla.btLogo != null) {
                        bmd.setBtLogo(gla.btLogo);  // 修改 不改动 启动状态
                    } else {
                        bmd.setBtLogo(null);
                    }


                    if (!"".equals(gla.btMailAddr) && gla.btMailAddr != null) {
                        bmd.setBtMailAddr(gla.btMailAddr);  // 修改 不改动 启动状态
                    } else {
                        bmd.setBtMailAddr(null);
                    }

                    if (!"".equals(gla.btName) && gla.btName != null) {
                        bmd.setBtName(gla.btName);  // 修改 不改动 启动状态
                    } else {
                        bmd.setBtName(null);
                    }


                    if (!"".equals(gla.btTaxNo) && gla.btTaxNo != null) {
                        bmd.setBtTaxNo(gla.btTaxNo);  // 修改 不改动 启动状态
                    } else {
                        bmd.setBtTaxNo(null);
                    }

                    if (!"".equals(gla.btTrueId) && gla.btTrueId != null) {
                        bmd.setBtTrueId(gla.btTrueId);  // 修改 不改动 启动状态
                    } else {
                        bmd.setBtTrueId(null);
                    }
                    if (!"".equals(gla.btRemarks) && gla.btRemarks != null) {
                        bmd.setBtRemarks(gla.btRemarks);  // 修改 不改动 启动状态
                    } else {
                        bmd.setBtRemarks(null);
                    }
                    if (!"".equals(gla.btSign) && gla.btSign != null) {
                        bmd.setBtSign(gla.btSign);  // 修改 不改动 启动状态
                    } else {
                        bmd.setBtSign(null);
                    }
                    if (!"".equals(gla.shopids) && gla.shopids != null) {
                        bmd.setShoptypeid(gla.shopids);  // 商品版本编号
                    } else {
                        bmd.setShoptypeid(null);
                    }
                    java.sql.Timestamp ts233 = new java.sql.Timestamp(System.currentTimeMillis()); //   bt_updateDt   timestamp ,   更新时间
                    bmd.setBtUpdateDt(ts233);
                    businessticketsRepositorys.save(bmd);


                } else {
                    BusinessticketsModel bmdsy = businessticketsRepositorys.getBbmodelByBtTaxNo(gla.btTaxNo);
                    if (bmdsy != null) {
                        //不为空  就是更新
                        if (!"".equals(gla.btAddrAndTel) && gla.btAddrAndTel != null) {
                            bmdsy.setBtAddrAndTel(gla.btAddrAndTel);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setBtAddrAndTel(null);
                        }
                        if (!"".equals(gla.btBankAccount) && gla.btBankAccount != null) {
                            bmdsy.setBtBankAccount(gla.btBankAccount);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setBtBankAccount(null);
                        }

                        if (!"".equals(gla.btLogo) && gla.btLogo != null) {
                            bmdsy.setBtLogo(gla.btLogo);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setBtLogo(null);
                        }
                        if (!"".equals(gla.firstreviewPerson) && gla.firstreviewPerson != null) {
                            bmdsy.setFirstreviewPerson(gla.firstreviewPerson);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setFirstreviewPerson(null);
                        }
                        if (!"".equals(gla.endreviewPerson) && gla.endreviewPerson != null) {
                            bmdsy.setEndreviewPerson(gla.endreviewPerson);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setEndreviewPerson(null);
                        }


                        if (!"".equals(gla.btName) && gla.btMailAddr != null) {
                            bmdsy.setBtMailAddr(gla.btMailAddr);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setBtMailAddr(null);
                        }

                        if (!"".equals(gla.btName) && gla.btName != null) {
                            bmdsy.setBtName(gla.btName);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setBtName(null);
                        }
                        if (!"".equals(gla.btSign) && gla.btSign != null) {
                            bmdsy.setBtSign(gla.btSign);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setBtSign(null);
                        }
                        if (!"".equals(gla.btTrueId) && gla.btTrueId != null) {
                            bmdsy.setBtTrueId(gla.btTrueId);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setBtTrueId(null);
                        }
                        if (!"".equals(gla.btRemarks) && gla.btRemarks != null) {
                            bmdsy.setBtRemarks(gla.btRemarks);  // 修改 不改动 启动状态
                        } else {
                            bmdsy.setBtRemarks(null);
                        }
                        if (!"".equals(gla.shopids) && gla.shopids != null) {
                            bmdsy.setShoptypeid(gla.shopids);  // 商品版本编号
                        } else {
                            bmdsy.setShoptypeid(null);
                        }
                        java.sql.Timestamp ts23 = new java.sql.Timestamp(System.currentTimeMillis());
                        bmdsy.setBtUpdateDt(ts23);  //   bt_updateDt   timestamp ,   更新时间
                        businessticketsRepositorys.save(bmdsy);


                    } else {
                        // 主键 没有查询出来， 税号 也没有查询出来 就是 插入  状态为 启用
                        BusinessticketsModel bmdss = new BusinessticketsModel();
                        if (!"".equals(gla.btAddrAndTel) && gla.btAddrAndTel != null) {
                            bmdss.setBtAddrAndTel(gla.btAddrAndTel);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setBtAddrAndTel(null);
                        }
                        if (!"".equals(gla.btBankAccount) && gla.btBankAccount != null) {
                            bmdss.setBtBankAccount(gla.btBankAccount);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setBtBankAccount(null);
                        }

                        if (!"".equals(gla.btLogo) && gla.btLogo != null) {
                            bmdss.setBtLogo(gla.btLogo);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setBtLogo(null);
                        }


                        if (!"".equals(gla.btMailAddr) && gla.btMailAddr != null) {
                            bmdss.setBtMailAddr(gla.btMailAddr);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setBtMailAddr(null);
                        }

                        if (!"".equals(gla.btName) && gla.btName != null) {
                            bmdss.setBtName(gla.btName);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setBtName(null);
                        }

                        if (!"".equals(gla.btTaxNo) && gla.btTaxNo != null) {
                            bmdss.setBtTaxNo(gla.btTaxNo);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setBtTaxNo(null);
                        }

                        if (!"".equals(gla.btTrueId) && gla.btTrueId != null) {
                            bmdss.setBtTrueId(gla.btTrueId);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setBtTrueId(null);
                        }
                        if (!"".equals(gla.btRemarks) && gla.btRemarks != null) {
                            bmdss.setBtRemarks(gla.btRemarks);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setBtRemarks(null);
                        }
                        if (!"".equals(gla.btSign) && gla.btSign != null) {
                            bmdss.setBtSign(gla.btSign);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setBtSign(null);
                        }


                        if (!"".equals(gla.firstreviewPerson) && gla.firstreviewPerson != null) {
                            bmdss.setFirstreviewPerson(gla.firstreviewPerson);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setFirstreviewPerson(null);
                        }
                        if (!"".equals(gla.endreviewPerson) && gla.endreviewPerson != null) {
                            bmdss.setEndreviewPerson(gla.endreviewPerson);  // 修改 不改动 启动状态
                        } else {
                            bmdss.setEndreviewPerson(null);
                        }
                        if (!"".equals(gla.shopids) && gla.shopids != null) {
                            bmdss.setShoptypeid(gla.shopids);  // 商品版本编号
                        } else {
                            bmdss.setShoptypeid(null);
                        }
                        bmdss.setBtStarStatus("启用");
                        java.sql.Timestamp ts2 = new java.sql.Timestamp(System.currentTimeMillis());
                        bmdss.setBtUpdateDt(ts2);  //   bt_updateDt   timestamp ,   更新时间
                        businessticketsRepositorys.save(bmdss);
                    }
                }
            }
            flag = true;
        } catch (Exception e) {

            logger.error("详细表精品保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        }
        return flag;
    }

    // 获取出所有的 开票的 信息  xxd 11.16
    @Override
    public PageData getBusinessticketsList(RequestBase request) {

        return this.repository.getBusinessAlllist(request.getPageSize(), request.getPageIndex());
    }


    // 更改状态 开票的
    @Override
    @Transactional
    public boolean saveBusinessticketsStatus(List<getBusinessticketsStatus> rel) {
        boolean flag = false;
        try {
            for (int i = 0; i < rel.size(); i++) {
                getBusinessticketsStatus item = rel.get(i);
                BusinessticketsModel modellist = businessticketsRepositorys.findOne(item.ids);

                java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis());
                modellist.setBtUpdateDt(ts);
                businessticketsRepositorys.save(modellist);
            }
        } catch (Exception e) {
            logger.error("开票状态更改失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        }
        return flag;

    }


    // 就是 更改 启动状态
    @Override
    @Transactional
    public boolean saveBusinessticketsControllerStatus(getBusinessticketsStatus item) {
        boolean flag = false;
        try {
            // 主表
            BusinessticketsModel modellist = businessticketsRepositorys.findOne(item.ids);
            if (modellist != null) {

                modellist.setBtStarStatus(item.status);
                java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis());
                modellist.setBtUpdateDt(ts);
                businessticketsRepositorys.save(modellist);
                flag = true;
            } else {
                flag = false;
            }
        } catch (Exception e) {
            logger.error("开票状态更改失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        }
        return flag;


    }

    public Map getpreIdByTaxNo(getBusinessticketsStatus relist) {

        BusinessticketsModel modellist = businessticketsRepositorys.getBbmodelByBtTaxNo(relist.status);
        Map retuMap = new HashMap();
        if (modellist != null && !"".equals(modellist)) {

            retuMap.put("id", modellist.getBtId());

        } else {

            retuMap.put("id", 0);

        }
        return retuMap;

    }

    // 11.17
    public List getBusniessByName(List<getBusinessticketsStatus> relist) {
        List<String> item = new ArrayList();
        // 根据名字 来查 出所有的 list
        for (int i = 0; i < relist.size(); i++) {
            getBusinessticketsStatus var = relist.get(i);
            if (var.status != null && !"".equals(var.status)) {
                item.add(var.status.toString());
            }
        }


        return repository.getBusniessByName(item);
    }

    @Transactional
    public boolean saveBusinessticketsRelyInfo(List<getBusinessticketsRelyInfo> re) {
        boolean flag = false;
        try {
            for (int i = 0; i < re.size(); i++) {

                getBusinessticketsRelyInfo item = re.get(i);
                BusinessticketsrelyModel itemodel = businessticketsRelyRepository.getBmodelByIdAndproductIds(item.productid, item.btId);
                if (itemodel == null || "".equals(itemodel)) {
                    // 如果 没有查出来， 就 插入
                    BusinessticketsrelyModel newmodel = new BusinessticketsrelyModel();

                    if (item.btId != 0 && !"".equals(item.btId)) {
                        newmodel.setBtTrueIds(item.btId);
                    }
                    if (item.productid != null && !"".equals(item.productid)) {
                        newmodel.setBtRelyProductId(item.productid);
                    }

                    if (item.VrTaxNo != null && !"".equals(item.VrTaxNo)) {
                        newmodel.setVrTicketsNo(item.VrTaxNo);
                    }
                    newmodel.setBtStatus("已导出");
                    java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis());
                    newmodel.setUpdateDt(ts);
                    businessticketsRelyRepository.save(newmodel);
                } else {
                    // 如果有 ， 就更新
                    if (item.VrTaxNo != null && !"".equals(item.VrTaxNo)) {
                        itemodel.setVrTicketsNo(item.VrTaxNo);
                    }
                    java.sql.Timestamp ts111 = new java.sql.Timestamp(System.currentTimeMillis());
                    itemodel.setUpdateDt(ts111);
                    businessticketsRelyRepository.save(itemodel);
                }
            }
            flag = true;
        } catch (Exception e) {
            logger.error("更新开票表失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        }
        return flag;
    }


    // 获取 开票详细信息
    public List getAfterMarketTicketDetailList(int ids, getBusinessticketsRelyInfo re) {
        BusinessticketsrelyModel item = businessticketsRelyRepository.getBmodelByIdAndproductIdsNotstatus(ids + "");

        if (item.getBtTrueIds() != 0 && !"".equals(item.getBtTrueIds())) {
            if (!"".equals(item.getVrTicketsNo()) && item.getVrTicketsNo() != null) {
                int trueId = item.getBtTrueIds();
                String texNo = item.getVrTicketsNo();
                if (re.trueTaxNo == null || "".equals(re.trueTaxNo)) {
                    // 如果 真实 为空
                    return businessticketsRelyRepository.getBmodelByIdAndVrTicketsNo(texNo, trueId);
                } else {
                    // 真实 不为空 那么 就是  直接把 真实 税号 更新进去
                    BusinessticketsrelyModel newitem = null;
                    List<BusinessticketsrelyModel> arrlist = new ArrayList<BusinessticketsrelyModel>();
                    List<BusinessticketsrelyModel> nolist = businessticketsRelyRepository.getBmodelByIdAndVrTicketsNo(texNo, trueId);
                    for (BusinessticketsrelyModel updatemodel : nolist) {
                        updatemodel.setTicketsNumber(re.trueTaxNo);
                        updatemodel.setBtStatus("已开票");
                        newitem = businessticketsRelyRepository.save(updatemodel);
                        arrlist.add(newitem);
                    }

                    return arrlist;
                }
            }
        }
        return null;
    }

    @Transactional
    public boolean saveShopDetailStatusAddninthDay(List<getBusinessticketsStatus> relist) {
        boolean flag = false;
        try {
            // 根据 传入的 状态 直接把 1
            for (int i = 0; i < relist.size(); i++) {
                getBusinessticketsStatus items = relist.get(i);
                报价精品详细表精品Model upmodel = 报价精品详细表精品repository.findOne(items.ids);
                upmodel.setIsDelete("1");
                报价精品详细表精品repository.save(upmodel);
            }
            flag = true;
        } catch (Exception e) {
            logger.error("更新报价精品详细表精品失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        }


        return flag;
    }


    @Transactional
    public boolean saveAfterMarketOrderAndAllDetail(getAfterMarketOrderAndAllDetail relists) {

        boolean flag = false;
        try {

            if (!"".equals(relists.relistes) && relists.relistes != null) {
                List<getzujian> relist = relists.relistes;
                for (int i = 0; i < relist.size(); i++) {

                    getzujian ritem = relist.get(i);
                    int dids = ritem.atrueid;
                    if (!"".equals(ritem.aid)) {
                        int cids = ritem.aid;
                        报价精品详细表精品Model threemodel = 报价精品详细表精品repository.findOne(cids);
                        if (threemodel != null && !"".equals(threemodel)) {
                            if (!"".equals(relists.asum)) {
                                int asum = relists.asum;
                                threemodel.set数量(asum);
                            }

                            threemodel.setOrderStatus("5");
                            报价精品详细表精品repository.save(threemodel);

                        } else {
                            报价精品详细表精品Model newmodel = new 报价精品详细表精品Model();
                            if (!"".equals(relists.asum)) {
                                int asums = relists.asum;
                                newmodel.set数量(asums);
                            }
                            newmodel.setComboId(ritem.acomid);
                            newmodel.setProductId(ritem.aproductId);
                            newmodel.set编号(ritem.atrueid);
                            newmodel.setOrderStatus("5");
                            报价精品详细表精品repository.save(newmodel);
                        }

                    } else {
                        报价精品详细表精品Model threemodelss = new 报价精品详细表精品Model();
                        if (!"".equals(relists.asum)) {
                            int asums = relists.asum;
                            threemodelss.set数量(asums);
                        }
                        threemodelss.setComboId(ritem.acomid);
                        threemodelss.setProductId(ritem.aproductId);
                        threemodelss.set编号(ritem.atrueid);
                        threemodelss.setOrderStatus("5");
                        报价精品详细表精品repository.save(threemodelss);


                    }


                    if (relists.aprice != null && !"".equals(relists.aprice)) {
                        报价精品表Model newmodel = 报价精品表Repository.findby编号(dids);
                        newmodel.set精品折后价((newmodel.get精品折后价()).add(new BigDecimal(relists.aprice)));
                        报价精品表Repository.save(newmodel);

                    }

                    if ((relists.aprice != null && !"".equals(relists.aprice)) || (!"".equals(relists.asum))) {
                        报价精品详细表ModelPK pknew = new 报价精品详细表ModelPK();
                        pknew.set编号(dids);
                        pknew.setId(ritem.acomid);
                        报价精品详细表Model newtwomodel = 报价精品详细表Repository.findOne(pknew);
                        if (relists.aprice != null && !"".equals(relists.aprice)) {
                            newtwomodel.set折后价((newtwomodel.get折后价()).add(new BigDecimal(relists.aprice)));
                        }
                        if (!"".equals(relists.asum)) {
                            int asums = relists.asum;
                            newtwomodel.set数量(asums);
                        }

                        报价精品详细表Repository.save(newtwomodel);

                    }


                }

            }

            flag = true;
        } catch (Exception e) {

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("更改后市场订单的状态为修改未提交", e);
            flag = false;
        }

        return flag;

    }

    /**
     * 获取集采精品清单
     * @param datee
     * @return
     */
    public List getAfterMarketWeekDailyDetail(String datee) {
        String[] dds = datee.split("-");
        String year = dds[0],month = dds[1];
        String bigAreaCode, bmbsCode = null;
        Map resultMap = new HashMap<>();
        Map allProducts = new HashMap<>(), //存放所有订购的精品
                bigarea, //单个大区{大区:"", 新车销量:0, 大区详细:[{}], 小区详细:[{}] }
                bigAreaDetails = null, //每个大区订购的精品 [产品编码: {产品名称:***,集采总成本:***, 集采采购数量:****, 单车采购成本:*****, 加装率:******}]
                permitDetail, //单个经销商{小区:"", 新车销量:0, 小区详细:[{}] }
                permitDetails, //每个经销商订购的精品 [产品编码: {产品名称:***,集采总成本:***, 集采采购数量:****, 单车采购成本:*****, 加装率:******}]
                productDetail,
                productDetails;

        //获取所有大区
        List<String> bigAreas = lsh经销商表Repository.findBIgAreasLiSt();
        for(Object bigArea : bigAreas){
            bigAreaCode = ((Object[]) bigArea)[1].toString();
            Map result = new HashMap();
            result.put("大区", bigAreaCode);
            result.put("新车销量", 0);
            result.put("大区详细", new HashMap<>()); //大区详细存放的是合并到大区的集采订单信息
            result.put("小区详细", new HashMap<>()); //小曲详细存放的是大区下经销商的统计信息，每个经销商的新车销量，集采订单信息

            resultMap.put(bigAreaCode, result);
        }

        //获取指定月份各经销商新车销量
        Integer permitAmount = 0, bigAreaAmount = 0;
        List<Map<String, Object>> saleList = imgtRepository.getCarSaleInfoes(year, month);
        for(Map<String, Object> sale:saleList){
            if(sale.get("大区_EN") == null) {
                logger.warn("大区_EN 为空。{}", JsonObjectUtils.writeAsJson(sale));
                continue;
            }

            bigAreaCode = sale.get("大区_EN").toString();
            bmbsCode = sale.get("许可_BMBS").toString();
            permitAmount = Integer.parseInt(sale.get("新车销量").toString());

            //统计大区的新车销量
            bigarea = (Map)resultMap.get(bigAreaCode);
            bigAreaAmount = Integer.parseInt(bigarea.get("新车销量").toString());
            bigarea.put("新车销量", bigAreaAmount + permitAmount);
            bigarea.put("大区详细", new HashMap<>());

            //统计经销商的新车销量
            permitDetails = (Map)bigarea.get("小区详细");
            permitDetail =(Map) permitDetails.get(bmbsCode);
            if(permitDetail == null){
                permitDetail = new HashMap<>();
            }
            permitDetail.put("小区", sale.get("许可_LSH"));
            permitDetail.put("新车销量", permitAmount);
            permitDetail.put("小区详细son", new HashMap());

            permitDetails.put(bmbsCode, permitDetail);
        }

        //获取指定月份各经销商精品集采信息
        List<Map> productList = repository.getPurchasedProductList4Dealer(year, month);
        Integer productId = null, purchaseNum;
        double purchasePrice = 0d;
        for(Map product:productList){
            bigAreaCode = product.get("大区_EN").toString();
            productId = Integer.parseInt(product.get("精品编号").toString());

            allProducts.put(productId, product.get("产品名称"));

            //输出大区的集采订单
            bigarea = (Map)resultMap.get(bigAreaCode);
            bigAreaDetails = (Map)bigarea.get("大区详细");

            productDetail = (Map)bigAreaDetails.get(productId);
            if(productDetail == null){
                productDetail = new HashMap<>();

                productDetail.put("产品名称", product.get("产品名称"));
                productDetail.put("单车采购成本", product.get("单车采购成本"));
            }
            purchaseNum = productDetail.get("集采采购数量") != null ? Integer.parseInt(productDetail.get("集采采购数量").toString()) : 0;
            purchasePrice = productDetail.get("集采总成本") != null ? Double.parseDouble(productDetail.get("集采总成本").toString()) : 0d;
            productDetail.put("集采采购数量", purchaseNum + Integer.parseInt(product.get("集采采购数量").toString()));
            productDetail.put("集采总成本", purchasePrice + Double.parseDouble(product.get("集采总成本").toString()));
            bigAreaDetails.put(productId, productDetail);

            //输出大区下经销商的集采订单
            permitDetails = (Map)bigarea.get("小区详细");
            permitDetail = (Map)permitDetails.get(product.get("许可_BMBS"));
            if(permitDetail == null){
                logger.warn(String.format("No permit detail found for 许可_BMBS=", product.get("许可_BMBS")));
                continue;
            }

            //输出经销商的集采订单详细
            productDetails = (Map) permitDetail.get("小区详细son");
            productDetail = (Map)productDetails.get(productId);
            if(productDetail == null){
                productDetail = new HashMap<>();
                productDetails.put(productId, productDetail);
                productDetail.put("产品名称", product.get("产品名称"));
                productDetail.put("单车采购成本", product.get("单车采购成本"));
            }
            productDetail.put("集采采购数量", purchaseNum + Integer.parseInt(product.get("集采采购数量").toString()));
            productDetail.put("集采总成本", purchasePrice + Double.parseDouble(product.get("集采总成本").toString()));
        }

        //格式转换，Map型转成List型
        List<Map> returnValue = new ArrayList<>();
        List<Map> listValue = null;
        for(Object tmp : resultMap.values()){
            bigarea = (Map) tmp;

            bigAreaDetails = (Map)bigarea.get("大区详细");//转换每个大区下的精品
            listValue = new ArrayList<>();
            for(Object bDetail : bigAreaDetails.values()){
                productDetail = (Map)bDetail;
                productDetail.put("加装率", NumberUtils.format(100 * Double.parseDouble(productDetail.get("集采采购数量").toString()) / Double.parseDouble(bigarea.get("新车销量").toString()), 2));
                listValue.add(productDetail);
            }
            for(Object pId : allProducts.keySet()){
                if(bigAreaDetails.containsKey(pId)) continue;

                Map newProduct = new HashMap();
                newProduct.put("集采总成本", "0");
                newProduct.put("集采采购数量", "0");
                newProduct.put("产品名称", allProducts.get(pId));
                newProduct.put("单车采购成本", "0");
                newProduct.put("加装率", "0");
                listValue.add(newProduct);
            }

            Collections.sort(listValue, new Comparator<Map>() {
                @Override
                public int compare(Map o1, Map o2) {
                    return o1.get("产品名称").toString().compareTo(o2.get("产品名称").toString());
                }
            });
            bigarea.put("大区详细", listValue);

            listValue = new ArrayList();
            permitDetails = (Map) bigarea.get("小区详细"); //获取大区下的经销商清单
            for(Object bDetail : permitDetails.values()){ //转换经销商
                permitDetail = (Map)bDetail;
                listValue.add(permitDetail);

                productDetails = (Map)permitDetail.get("小区详细son"); //转换每个经销商下的精品
                productList = new ArrayList<>();
                for(Object detail : productDetails.values()){
                    productDetail = (Map)detail;
                    productDetail.put("加装率", NumberUtils.format(100 * Double.parseDouble(productDetail.get("集采采购数量").toString()) / Double.parseDouble(permitDetail.get("新车销量").toString()), 2));

                    productList.add(productDetail);
                }
                for(Object pId : allProducts.keySet()){
                    if(productDetails.containsKey(pId)) continue;

                    Map newProduct = new HashMap();
                    newProduct.put("集采总成本", "0");
                    newProduct.put("集采采购数量", "0");
                    newProduct.put("产品名称", allProducts.get(pId));
                    newProduct.put("单车采购成本", "0");
                    newProduct.put("加装率", "0");
                    productList.add(newProduct);
                }

                Collections.sort(productList, new Comparator<Map>() {
                    @Override
                    public int compare(Map o1, Map o2) {
                        return o1.get("产品名称").toString().compareTo(o2.get("产品名称").toString());
                    }
                });

                permitDetail.put("小区详细son", productList);
            }

            bigarea.put("小区详细", listValue);

            returnValue.add(bigarea);
        }

        return returnValue;
    }

    // 把 第一列 第二列以后的 搞定
    private List weekdailytwo(String years, String months, String bigCitypermitDa, List proid, String sons) {
        List listMap = new ArrayList();
        for (int i = 0; i < proid.size(); i++) {
            Map xmap = (Map) proid.get(i);
            String prodson = xmap.get("productId").toString();
            Lsh精品信息Model names = lsh精品信息Repository.findBy精品编号productId(Integer.parseInt(prodson));

            // 对应的 大区的 详细
            List MapList1 = repository.getPurchasedProductList(years, months);
            String numdde = null;
            if (names == null) {
                numdde = "没有名字";
            } else {
                numdde = names.get产品名称();
            }
            Map itemsom = new HashMap();
            if (MapList1.size() > 0) {
                itemsom = (Map) MapList1.get(0);
                if (itemsom.get("集采采购数量") != null) {
                    String fenzi = itemsom.get("集采采购数量").toString();
                    double a = Double.parseDouble(fenzi);
                    double b = Double.parseDouble(sons);
                    DecimalFormat df = new DecimalFormat("####0.00");
                    if (sons.equals("0")) {
                        itemsom.put("加装率", "0");
                    } else {
                        double c = a / b * 100;
                        itemsom.put("加装率", df.format(c) + "%");
                    }
                    itemsom.put("产品名称", numdde);
                } else {

                    itemsom.put("集采总成本", "0");
                    itemsom.put("集采采购数量", "0");
                    itemsom.put("产品名称", numdde);
                    itemsom.put("单车采购成本", "0");
                    itemsom.put("加装率", "0");
                }

            } else {
                itemsom.put("集采总成本", "0");
                itemsom.put("集采采购数量", "0");
                itemsom.put("产品名称", numdde);
                itemsom.put("单车采购成本", "0");
                itemsom.put("加装率", "0");
            }
            listMap.add(itemsom);

        }
        return listMap;
    }


    // 把 第一列 第二列 搞定
    private String weekdailyone(String years, String months, String bigCitypermitDa) {
        List MapList1 = repository.getAfterMarketWeekDailyDetailOne(years, months, bigCitypermitDa);

        Map m1 = null;
        String y1 = null;
        if (MapList1.size() > 0) {
            m1 = (Map) MapList1.get(0);

            if (!"".equals(m1.get("新车销量")) && m1.get("新车销量") != null) {
                return m1.get("新车销量").toString();
            } else {
                return "0";
            }
        } else {
            return "0";
        }

    }

    public List getAfterMarketWeekDailyDetailBysole(String datee) {
        String[] dds = datee.split("-");
        String years = dds[0];
        String months = dds[1];
        List MapList = new ArrayList();
        // 把所有的 满足条件的 productId 拿出来
        List plist = repository.getplistbysole();
        // 拿出来 所有的大区 不重复的
        List weeklist = repository.getAfterMarketWeekDailyDetailOneDaqu();
        for (int i = 0; i < weeklist.size(); i++) {
            List MapList1 = new ArrayList();
            List MapList2 = new ArrayList();
            List MapList3 = new ArrayList();
            List MapList4 = new ArrayList();
            Map ssd = (Map) weeklist.get(i);
            Map itemMap = new HashMap();
            String bigCitypermitDa = ssd.get("大区_EN").toString();
            // 这个 是 经销商 和 新车销量
            String sumn = weekdailyone(years, months, bigCitypermitDa);
            itemMap.put("新车销量", sumn);
            itemMap.put("大区", bigCitypermitDa);

            // 先把 所有  大区下面的额 小区 查出来
            List smallCity = repository.getplists(bigCitypermitDa);
            // 对应的  prodcutid 的 和 小区的 对应的
            List smallCitydetail = weekdailytwothreeBysole(years, months, smallCity, plist);
            // 把对应的 大区的 东西全部 填充
            List BigCityDetail = weekdailytwo(years, months, bigCitypermitDa, plist, sumn);
            itemMap.put("大区详细", BigCityDetail);
            itemMap.put("小区详细", smallCitydetail);

            MapList.add(itemMap);
        }
        return MapList;


    }


    //根据 小区+ 厂商名字
    private List weekdailytwothreeBysole(String years, String months, List sonlistthree, List plist) {
        List listMap = new ArrayList(); //                         小区的 许可list   pdoid 的list
        for (int i = 0; i < sonlistthree.size(); i++) {
            Map xmap = (Map) sonlistthree.get(i);
            String permit = xmap.get("permits").toString();
            // 拿出 对应的 销量
            List sumone = repository.getAfterMarkettwoWeekDailyDetailtwoThree(permit, years, months);
            String fenmu = "0";
            Map itemmap = new HashMap();
            if (sumone.size() > 0) {
                itemmap = (Map) sumone.get(0);
                fenmu = itemmap.get("新车销量").toString();
            } else {
                itemmap.put("新车销量", "0");
            }
            itemmap.put("小区", permit);

            // 小区的里面 详细
            List nidmeson = getAfterMarkettwoWeekDailyDetailtwoThreesonbysole(years, months, permit, plist, fenmu);
            itemmap.put("厂商详细", nidmeson);
            listMap.add(itemmap);
        }

        return listMap;
    }


    private List getAfterMarkettwoWeekDailyDetailtwoThreesonbysole(String years, String months, String permit, List proid, String fenmu) {
        List listMap = new ArrayList();
        // 小区的 详细
        for (int i = 0; i < proid.size(); i++) {
            Map xmap = (Map) proid.get(i);
            String productid = xmap.get("厂商").toString();

            // 拿出 小区的 详细 (实际 只有 一行 数据， 拿出来 就行了   )
            List nanidesson = repository.getAfterMarkettwoWeekDailyDetailtwosonsbysole(years, months, permit, productid);
            Map itemsom = new HashMap();
            itemsom.put("厂商", permit);
            if (nanidesson.size() > 0) {
                itemsom = (Map) nanidesson.get(0);
                if (itemsom.get("集采采购数量") != null) {
                    String fenzi = itemsom.get("集采采购数量").toString();
                    double a = Double.parseDouble(fenzi);
                    double b = Double.parseDouble(fenmu);
                    DecimalFormat df = new DecimalFormat("####0.00");
                    if (fenmu.equals("0")) {
                        itemsom.put("加装率", "0");
                    } else {
                        double c = a / b * 100;

                        itemsom.put("加装率", df.format(c) + "%");
                    }

                } else {

                    itemsom.put("集采采购数量", "0");
                    itemsom.put("加装率", "0");
                }

            } else {
                itemsom.put("集采采购数量", "0");
                itemsom.put("加装率", "0");
            }
            listMap.add(itemsom);
        }
        return listMap;
    }


    public List getAfterMarketWeekonesones() {
        try {
            return repository.findAllbysqland();//

        } catch (Exception e) {
            logger.error("getAfterMarketWeekonesones方法", e);
            return null;
        }
    }

    public PageData getAfterMarketWeekonestwo(RequestBase re) {
        return repository.getAfterMarketWeekonestwo(re.getPageSize(), re.getPageIndex());

    }

    public List getAfterMarketWeekonestwos(RequestBase re) {
        return repository.getAfterMarketWeekonestwos();

    }

    public boolean saveAfterMarketWeekonesthree(AfterMarketService.getAfterMarketOrderShopCarDetail re) {

        try {
            List<Lsh精品分类Model> nndds = lsh精品分类Repository.getIdBytwobrother(re.type, re.备注);
            for (int i = 0; i < nndds.size(); i++) {
                Lsh精品分类Model nndd = nndds.get(i);
                nndd.setShoptypeid(null);
                nndd.setSoleshopid(null);
                lsh精品分类Repository.save(nndd);
            }
            return true;
        } catch (Exception e) {
            logger.error("getAfterMarketWeekonesones方法", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return false;
    }

    public boolean saveAfterMarketWeekonesfour(List<AfterMarketService.GetAfterQualityInfoByParams> re) {
        boolean flag = false;
        try {

            for (int i = 0; i < re.size(); i++) {
                GetAfterQualityInfoByParams newitem = re.get(i);
                // 根据 传入的   商品 + 开票  把  这个 同名的 全部删除掉
                List<Lsh精品分类Model> model = lsh精品分类Repository.getIdBytwobrother(newitem.productNum, newitem.source);
                if (model.size() > 0) {
                    for (int j = 0; j < model.size(); j++) {
                        Lsh精品分类Model sonmodel = model.get(j);
                        sonmodel.setShoptypeid(null);
                        sonmodel.setSoleshopid(null);
                        lsh精品分类Repository.save(sonmodel);
                    }
                }
            }
            flag = savebugfix(re);

        } catch (Exception e) {
            logger.error("删除精品分类出错", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        }
        return flag;
    }


    private boolean savebugfix(List<AfterMarketService.GetAfterQualityInfoByParams> re) {
        boolean flag = false;
        try {
            for (int i = 0; i < re.size(); i++) {
                GetAfterQualityInfoByParams newitem = re.get(i);
                Lsh精品分类Model model = lsh精品分类Repository.findOne(newitem.qualityId);

                if (newitem.productNum != null && !"".equals(newitem.productNum)) {
                    model.setShoptypeid(newitem.productNum);
                }
                if (newitem.source != null && !"".equals(newitem.source)) {
                    model.setSoleshopid(newitem.source);
                }

                lsh精品分类Repository.save(model);
            }
            flag = true;
        } catch (Exception e) {
            logger.error("删除精品分类出错", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        }
        return flag;

    }


    public Map getAddorderstatusshopids(GetAfterQualityInfoByParams re) {
        Map resulm = new HashMap();
        List<Lsh精品分类Model> oned = lsh精品分类Repository.getIdBytwobrothershoptypeid(re.productNum);//////////
        if (oned.size() != 0 && !"".equals(oned)) {
            resulm.put("status", "1");

        } else {
            List<Lsh精品分类Model> oneds = lsh精品分类Repository.getIdBytwobrothersoleshopid(re.source);
            if (oneds.size() != 0 && !"".equals(oneds)) {
                resulm.put("status", "2");
            } else {
                resulm.put("status", "0");
            }
        }
        return resulm;
    }


    public boolean saveStausBusinesSoleids(GetAfterQualityInfoByParams re) {
        List<BusinessticketsModel> sonlist = businessticketsRepositorys.findAll();
        boolean flag = false;
        try {
            for (int i = 0; i < sonlist.size(); i++) {

                BusinessticketsModel sons = sonlist.get(i);
                sons.setShoptypeid(re.productNum);
                businessticketsRepositorys.save(sons);
            }

            flag = true;
        } catch (Exception e) {
            logger.error("删除精品分类出错", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        }
        return flag;
    }

    public ResultData getVendorMailList(RequestBase re) {
        ResultData resultData = new ResultData();
        String msg = "";
        String flag = "";
        List relist = new ArrayList();
        PageData pageData = new PageData(relist, relist.size());
        try {
            pageData = repository.getVendorMailList(re.getPageIndex(), re.getPageSize());
            // relist = tPrdSupplierMailSettingRepository.findAll();////查询 数据的
            //pageData.setData(relist);
            resultData.setPageData(pageData);
            flag = "true";
        } catch (Exception e) {
            logger.error("查询邮件信息失败", e);
            flag = "false";
        }
        resultData.setResult(flag);
        return resultData;
    }

    // 更改状态
    public ResultData deleteSingleVendorMail(getVendorInfos re, String username, String permit) {
        ResultData rd = new ResultData();
        String msg = "";
        String flag = "";
        List resultlist = new ArrayList();
        PageData pg = new PageData(resultlist, resultlist.size());
        int productids = 0;
        try {//////
            if (re.productId != null) {
                productids = Integer.parseInt(re.productId);
            }
            //TPrdSupplierMailSettingModel  mailmodle= tPrdSupplierMailSettingRepository.getModelByProductIdAndSupplieId(re.vendorName,productids);
            TPrdSupplierMailSettingModel mailmodle = tPrdSupplierMailSettingRepository.findOne(productids);
            mailmodle.setIsDeleted(1);//0 启用 1 删除
            mailmodle.setUpdateUserId(username);
            java.sql.Date updaDate = new java.sql.Date(System.currentTimeMillis());
            mailmodle.setUpdateDate(updaDate);
            TPrdSupplierMailSettingModel newmailmodle = tPrdSupplierMailSettingRepository.save(mailmodle);
            resultlist.add(newmailmodle);
            pg.setData(resultlist);
            rd.setPageData(pg);
            flag = "true";
            msg = "删除成功";
        } catch (Exception e) {
            logger.error("删除精品邮件信息出错", e);
            flag = "false";
            msg = "删除失败";

        }
        rd.setMessage(msg);
        rd.setResult(flag);
        return rd;
    }

    // 批量的 导入 或者 编辑
    public ResultData updateSingleVendorMailInfo(List<getVendorDetailInfos> re, String username, String permit) {

        ResultData rd = new ResultData();
        String flag = "";
        String msg = "";
        PageData pg = new PageData();
        try {
            for (int i = 0; i < re.size(); i++) {
                getVendorDetailInfos items = re.get(i);

                if (items.id != null) {
                    // 直接进行下一步的更新
                    flag = updateMailInfoAction(items, username, permit);
                } else {
                    String supid = items.vendorName;
                    int pid = Integer.parseInt(items.productId);
                    TPrdSupplierMailSettingModel newmailmodle = tPrdSupplierMailSettingRepository.getModelByProductIdAndSupplieId(supid, pid);
                    if (newmailmodle != null) {
                        flag = updateCunzaiModel(newmailmodle, items, username);
                    } else {
                        // 如果 没有传入主键 那么 执行的 插入的 操作 并且 根据 厂商和 pid 没有找到 相应的
                        flag = insertMailInfoAction(items, username, permit);
                    }
                }
            }
            msg = "编辑成功";
        } catch (Exception e) {
            logger.error("编辑失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            msg = "编辑失败";
            flag = "false";
        }
        rd.setMessage(msg);
        rd.setResult(flag);
        return rd;
    }

    private String updateCunzaiModel(TPrdSupplierMailSettingModel newmailmodle, getVendorDetailInfos item, String username) {
        String flag = "";
        try {
            newmailmodle.setUpdateDate(new java.sql.Date(System.currentTimeMillis()));
            newmailmodle.setUpdateUserId(username);
            if (item.addrCc != null) {
                newmailmodle.setAddrCc(item.addrCc);
            }
            if (item.addrTo != null) {
                newmailmodle.setAddrTo(item.addrTo);
            }
            if (item.title != null) {
                newmailmodle.setTitle(item.title);
            }
            if (item.content != null) {
                newmailmodle.setContent(item.content);
            }
            newmailmodle.setIsDeleted(0);
            tPrdSupplierMailSettingRepository.save(newmailmodle);
            flag = "true";
        } catch (Exception e) {
            logger.error("更新 id 不存在 且 厂商以前有 邮件信息 失败", e);
            flag = "false";
        }
        return flag;


    }


    private String updateMailInfoAction(getVendorDetailInfos item, String username, String permit) {
        String flag = "";
        try {
            TPrdSupplierMailSettingModel newmailmodle = tPrdSupplierMailSettingRepository.findOne(Integer.parseInt(item.id));
            newmailmodle.setUpdateDate(new java.sql.Date(System.currentTimeMillis()));
            newmailmodle.setUpdateUserId(username);
            if (item.addrCc != null) {
                newmailmodle.setAddrCc(item.addrCc);
            }
            if (item.addrTo != null) {
                newmailmodle.setAddrTo(item.addrTo);
            }
            if (item.title != null) {
                newmailmodle.setTitle(item.title);
            }
            if (item.content != null) {
                newmailmodle.setContent(item.content);
            }
            if (item.vendorName != null) {
                newmailmodle.setSupplierId(item.vendorName);
            }
            if (item.productId != null) {
                newmailmodle.setProductId(Integer.parseInt(item.productId));
            }
            newmailmodle.setIsDeleted(0);
            tPrdSupplierMailSettingRepository.save(newmailmodle);
            flag = "true";
        } catch (Exception e) {
            logger.error("更新 邮件信息 失败", e);
            flag = "false";
        }
        return flag;
    }

    private String insertMailInfoAction(getVendorDetailInfos item, String username, String permit) {
        String flag = "";
        try {
            TPrdSupplierMailSettingModel newmailmodle = new TPrdSupplierMailSettingModel();
            newmailmodle.setUpdateDate(new java.sql.Date(System.currentTimeMillis()));
            newmailmodle.setUpdateUserId(username);
            newmailmodle.setCreateDate(new java.sql.Date(System.currentTimeMillis()));
            newmailmodle.setCreateUserId(username);
            if (item.addrCc != null) {
                newmailmodle.setAddrCc(item.addrCc);
            }
            if (item.addrTo != null) {
                newmailmodle.setAddrTo(item.addrTo);
            }
            if (item.title != null) {
                newmailmodle.setTitle(item.title);
            }
            if (item.content != null) {
                newmailmodle.setContent(item.content);
            }
            if (item.vendorName != null) {
                newmailmodle.setSupplierId(item.vendorName);
            }
            if (item.productId != null) {
                newmailmodle.setProductId(Integer.parseInt(item.productId));
            }// 首次 默认为  启用
            newmailmodle.setIsDeleted(0);
            tPrdSupplierMailSettingRepository.save(newmailmodle);
            flag = "true";
        } catch (Exception e) {
            logger.error("更新 邮件信息 失败", e);
            flag = "false";
        }
        return flag;
    }

    /**
     * 根据精品编号判断是否需要更新套餐信息
     *
     * @return
     */
    @Override
    public int isUpdateCombInfoByQuaId(IsUpdateCombInfoByQuaId param) throws ParseException {
        java.sql.Date startDate = DateFormatUtils.parseStrToSqlDate(param.精品开始日期);
        java.sql.Date endDate = DateFormatUtils.parseStrToSqlDate(param.精品结束日期);
        int status = 1;
        Integer quaId = Integer.valueOf(param.精品编号);
        List<Lsh精品套餐详细Model> model精品套餐List = lsh精品套餐详细Repository.findDetailRecordByQualityId(quaId);
        List<Lsh套餐信息Model> arrList = new ArrayList<>();
        for (int i = 0; i < model精品套餐List.size(); i++) {
            Lsh精品套餐详细Model model精品套餐 = model精品套餐List.get(i);
            List<Lsh套餐信息Model> model套餐List = lsh套餐信息Repository.findListById(model精品套餐.get套餐编号(), "是");
            arrList.addAll(model套餐List);
        }
        boolean isContinue = false;
        for (int i = 0; i < arrList.size(); i++) {
            Lsh套餐信息Model model套餐 = arrList.get(i);
            //如果精品的开始时间<=套餐的开始时间 并且 精品的结束时间 >=套餐的结束时间
            if (startDate.getTime() <= model套餐.get套餐开始日期().getTime() &&
                    endDate.getTime() >= model套餐.get套餐结束日期().getTime()) {
                status = 1;//既不保存套餐开始日期，也不保存套餐结束日期
            } else {
                //精品的开始时间 > 套餐的开始时间，更新套餐的开始时间为精品的开始时间
                if (startDate.getTime() > model套餐.get套餐开始日期().getTime()) {
                    status = 2;//保存套餐开始日期
                }
                //精品的结束时间 < 套餐的结束时间，更新套餐的结束时间为精品的结束时间
                if (endDate.getTime() < model套餐.get套餐结束日期().getTime()) {
                    status = 3;//保存套餐结束日期
                }
                if (startDate.getTime() > model套餐.get套餐开始日期().getTime() &&
                        endDate.getTime() < model套餐.get套餐结束日期().getTime()) {
                    status = 4;//保存套餐开始和结束日期
                }
                isContinue = true;
                break;
            }
        }
        return status;
    }

    @Override
    @Transactional
    public ResultData deleteProductInfo(Integer productId) {
        // 1、验证后市场产品是否被使用
        List productQuotations = afterMarketRepository.getProductQuotation(productId);
        if (productQuotations != null && !productQuotations.isEmpty()) {
            return new ResultData("false","此后市场产品已被使用，无法删除！",null);
        }

        // 2、查找需要删除的表数据
        Lsh精品信息Model product = lsh精品信息Repository.findBy精品编号productId(productId);  // lsh精品信息
        if (product == null) {
            return new ResultData("false","数据不存在，删除失败！");
        }
        Lsh精品促销Model promotion = lsh精品促销Repository.findByProductId(productId); // lsh精品促销
        List<Lsh精品适用车型Model> vehicles = lsh精品适用车型Repository.findCarRecordByQualityId(productId); // lsh精品适用车型
        List<Lsh精品适用区域Model> regions = lsh精品适用区域Repository.findAreaRecordByQualityId(productId); // lsh精品适用区域
        List<Lsh精品图片Model> photos = lsh精品图片Repository.findPicRecordByQualityId(productId); // lsh精品图片
        List<Map<String,Object>> details = afterMarketRepository.getProductPackageDetail(productId); // lsh精品套餐详细
        List<Map<String,Object>> packages = afterMarketRepository.getPackageInfo(productId); // lsh套餐信息

        // 3、把待删除的表数据放入回收表
            // 精品信息
        TDataRecycleModel productRecycle = new TDataRecycleModel();
        productRecycle.setPid(null);
        productRecycle.setObjectType("lsh精品信息");
        productRecycle.setObjectName(product.get产品名称());
        productRecycle.setObjectContent(JSON.toJSONString(product));
        productRecycle.setCreateTime(new Timestamp(new Date().getTime()));
        dataRecycleRepository.save(productRecycle);
            // 精品促销
        if (promotion != null) {
            TDataRecycleModel promotionRecycle = new TDataRecycleModel();
            promotionRecycle.setPid(productRecycle.getId());
            promotionRecycle.setObjectType("lsh精品促销");
            promotionRecycle.setObjectName(null);
            promotionRecycle.setObjectContent(JSON.toJSONString(promotion));
            promotionRecycle.setCreateTime(new Timestamp(new Date().getTime()));
            dataRecycleRepository.save(promotionRecycle);
        }
        if (vehicles != null && !vehicles.isEmpty()) {
            // 精品适用车型
            TDataRecycleModel vehiclesRecycle = new TDataRecycleModel();
            vehiclesRecycle.setPid(productRecycle.getId());
            vehiclesRecycle.setObjectType("lsh精品适用车型");
            vehiclesRecycle.setObjectName(null);
            vehiclesRecycle.setObjectContent(JSON.toJSONString(vehicles));
            vehiclesRecycle.setCreateTime(new Timestamp(new Date().getTime()));
            dataRecycleRepository.save(vehiclesRecycle);
        }
        if (regions != null && !regions.isEmpty()) {
            // 精品适用区域
            TDataRecycleModel regionsRecycle = new TDataRecycleModel();
            regionsRecycle.setPid(productRecycle.getId());
            regionsRecycle.setObjectType("lsh精品适用区域");
            regionsRecycle.setObjectName(null);
            regionsRecycle.setObjectContent(JSON.toJSONString(regions));
            regionsRecycle.setCreateTime(new Timestamp(new Date().getTime()));
            dataRecycleRepository.save(regionsRecycle);
        }
        if (photos != null && !photos.isEmpty()) {
            // lsh精品图片
            TDataRecycleModel photoRecycle = new TDataRecycleModel();
            photoRecycle.setPid(productRecycle.getId());
            photoRecycle.setObjectType("lsh精品图片");
            photoRecycle.setObjectName(null);
            photoRecycle.setObjectContent(JSON.toJSONString(photos));
            photoRecycle.setCreateTime(new Timestamp(new Date().getTime()));
            dataRecycleRepository.save(photoRecycle);
        }
        if (details != null && details.isEmpty()) {
            // lsh精品套餐详细
            TDataRecycleModel detailsRecycle = new TDataRecycleModel();
            detailsRecycle.setPid(productRecycle.getId());
            detailsRecycle.setObjectType("lsh精品套餐详细");
            detailsRecycle.setObjectName(null);
            detailsRecycle.setObjectContent(JSON.toJSONString(details));
            detailsRecycle.setCreateTime(new Timestamp(new Date().getTime()));
            dataRecycleRepository.save(detailsRecycle);

            if (packages != null && !packages.isEmpty()) {
                // lsh套餐信息
                TDataRecycleModel packagesRecycle = new TDataRecycleModel();
                packagesRecycle.setPid(detailsRecycle.getId());
                packagesRecycle.setObjectType("lsh套餐信息");
                packagesRecycle.setObjectName(null);
                packagesRecycle.setObjectContent(JSON.toJSONString(packages));
                packagesRecycle.setCreateTime(new Timestamp(new Date().getTime()));
                dataRecycleRepository.save(packagesRecycle);
            }
        }

        // 4、删除表数据
            // 删除精品促销
        if (promotion != null) {
            lsh精品促销Repository.delete(promotion);
        }
            // 删除精品适用车型
        if (vehicles != null && !vehicles.isEmpty()) {
            for (Lsh精品适用车型Model vehicle : vehicles) {
                lsh精品适用车型Repository.delete(vehicle);
            }
        }
            // 删除精品适用区域
        if (regions != null && !regions.isEmpty()) {
            for (Lsh精品适用区域Model region : regions) {
                lsh精品适用区域Repository.delete(region);
            }
        }
            // 删除精品图片
        if (photos != null && !photos.isEmpty()) {
           for (Lsh精品图片Model photo : photos ) {
               lsh精品图片Repository.delete(photo);
            }
        }
            // 删除精品套餐详细
        if (details != null && !details.isEmpty()) {
            for (Map<String,Object> detail : details) {
                lsh精品套餐详细Repository.deleteByPackageIdAndProductId((Integer)(detail.get("套餐编号")),(Integer)(detail.get("精品编号")));
            }
        }
            // 删除套餐信息
        if (packages != null && !packages.isEmpty()) {
            for (Map<String,Object> pack : packages) {
                lsh套餐信息Repository.deleteById((Integer)(pack.get("套餐编号")));
            }
        }
            // 删除精品信息
       lsh精品信息Repository.delete(product);

        return new ResultData("true","删除成功",null);
    }

    @Override
    public List<BoutiqueModel> findListBySourceAndClassifyId(Integer classifyId, String source){
        List<BoutiqueModel> list = null;
        try{
            list = boutiqueRepository.findListBySourceAndClassifyId(classifyId,source);
        }catch (Exception e){
          logger.error("查询精品分类异常",e);
        }
        return list;
    }

    /**
     * 调用产品组后市场精品查询接口
     * @param permit
     * @param username
     * @param shopId
     * @param shopName
     * @param unit
     * @param salePrice
     * @param cheXing
     * @param sort
     * @param thisPage
     * @param pageSize
     * @return
     */
    @Override
    public AfterMarketObj GetAfterMarketInfoFromOther(String permit, String username, String shopId, String shopName,
                                                              String unit, String salePrice, String cheXing, String sort,
                                                              int thisPage, int pageSize) {
        AfterMarketObj afterMarketObj = null;
        String urlHead = this.environment.getRequiredProperty("soa.after.url", String.class);
        String url = urlHead + "/shop/getShopInfoByCompIdAndShopInfo";
        JsonObject param = new JsonObject();
        param.addProperty("compId", permit);
        if (thisPage > 0) {
            param.addProperty("thisPage", thisPage);
        } else {
            param.addProperty("thisPage", 1);
        }
        if (pageSize > 0) {
            param.addProperty("pageSize", pageSize);
        } else {
            param.addProperty("pageSize", 15);
        }
        if (!Strings.isNullOrEmpty(shopId)) param.addProperty("shopId", shopId);
        if (!Strings.isNullOrEmpty(shopName)) param.addProperty("shopName", shopName);
        if (!Strings.isNullOrEmpty(unit)) param.addProperty("unit", unit);
        if (!Strings.isNullOrEmpty(salePrice)) param.addProperty("salePrice", salePrice);
        if (!Strings.isNullOrEmpty(cheXing)) param.addProperty("cheXing", cheXing);
        if (!Strings.isNullOrEmpty(sort)) param.addProperty("sort", sort);
        logger.info("调用第三方精品查询接口，获取精品信息");
        String returnValues = com.iris.live.services.common.reconsitution.HttpTools.sendPost(url, param.toString(), permit, username);
        if (!Strings.isNullOrEmpty(returnValues)) {
            Gson gson = new Gson();
            logger.info("将获取的第三方精品信息转换为AfterMarketResult--bean对象");
            AfterMarketResult afterMarketResult = gson.fromJson(returnValues, AfterMarketResult.class);
            if (afterMarketResult != null && !Strings.isNullOrEmpty(afterMarketResult.getObj())) {
                logger.info("将获取的第三方精品信息转换为AfterMarketObj--bean对象");
                afterMarketObj = gson.fromJson(afterMarketResult.getObj(), AfterMarketObj.class);
            }
        }
        return afterMarketObj;
    }

    @Override
    public PermitCodeModel getCompanyCode(String permit) {
        return permitCodeRepository.findByPermit(permit);
    }
}
